Why C# Won't Allow Field Initializer with Non-Static Fields

Why C# won't allow field initializer with non-static fields?

I'm more interested with the reason/logic for why it was restricted. just for curiosity.

If you read the C# Language Spec, 10.11.3, it hints as to the rationale here. In discussing variable initializers:

It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body.

Since these are "inserted before the constructor", they are being executed prior to this being valid, so allowing you to refer to other members (effectively this) would be problematic.

Note that this is consistent with how static fields work, as well. In both cases, you are allowed to access static data, but not instance data. The error message you receive ("A field initializer cannot reference the non-static field, method, or property") directly notes this.

A field initializer cannot reference the non-static field method or property

The correct syntax should be:

int count, xmin, xmax, ymin, ymax = 0;

EDIT:

Sample Image

Your original code seems to work no?

EDIT2:

Well ofcourse that won't work in a field initializer!

A field initializer cannot refer to other instance fields.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields

You can probs move the init code to your constructor if you really want - something like:

int count = 3, xmin, xmax, ymin, ymax;

void MyCtor()
{
xmin = xmax = ymin = ymax = count;
}

A field initializer cannot reference the non-static field c#

You cannot concat multiple string fields in a class to initialize them because it is not allowed that the variable initializer for an instance field references the instance being created(like other properties or fields) .

Use the constructor instead:

public Form1()
{
InitializeComponent();

localhost = "blah ..."; // initialize this string
myconnectionstring = "Server=" + localhost + "; Database=amepos2015; Uid=root; Pwd=fatehshah";

labelget();
}

string localhost = null;
string myconnectionstring = null;

The reason is that the compiler wants to prevent you from errors that would happen if you change the order of the fields. So it's not allowed in the first place.

Error 1 A field initializer cannot reference the non-static field, method, or property

Just move the initialization of class1 into a constructor:

class Form1 {
int a = 0;

Class1 obj1;

public Form1() {
obj1 = new Class1(a);
}
}

field initializer cannot reference the non-static field

Since the fields in Globals are not static, you need an instance of Globals to access them. Each instance of Globals will have its own set of fields.

Globals g = new Globals();

Then, you can access the fields of this instance:

g.Reader, g.Writer, etc

But, you can also use static fields. You can also make Globals a static class if all the members are static:

public static class Globals
{
public static Boolean Ready = false;
public static TcpClient Client = new TcpClient(server, port);
public static NetworkStream NwStream = Client.GetStream();
public static StreamReader Reader = new StreamReader(NwStream);
public static StreamWriter Writer = new StreamWriter(NwStream);
}

Then, you can access the fields by supplying the class name:

Globals.Reader, Globals.Writer, etc

LazyT Lazy loading error : A field initializer cannot reference the non-static field, method, or property

That initializer would require this to be passed into a capture-class, and this is not available from a field-initializer. However, it is available in a constructor:

private readonly Lazy<Progress> m_progress;
public MyType()
{
m_progress = new Lazy<Progress>(() =>
{
long totalBytes = m_transferManager.TotalSize();
return new Progress(totalBytes);
});
}

Personally, I'd just use the get accessor, though ;p

Why can't non-static fields be initialized inside structs?

Have a look at Why Can't Value Types have Default Constructors?

Calling a class with Blazor failing a field initializer cannot reference the nonstatic field, method, or property

Your issue is not specific to Blazor... You cannot initialize Teststring with a value from something that is not yet exist.

Instance fields cannot be used to initialize other instance fields
outside a method. If you are trying to initialize a variable
outside a method, consider performing the initialization inside the
class constructor

Or a method such as the OnInitialized lifecycle method...

You can do that like this:

@code {
testingClass t = new testingClass();
string Teststring => t.TestResponse();

public class testingClass
{
public string TestResponse()
{
return "hello world";
}
}
}

You can also do that like the code snippet below, which is the preferred way:

@code {
// Define the variables
testingClass t;
string Teststring;

protected override void OnInitialized()
{
// Instantiate your object
t = new testingClass();
// and then use it
Teststring = t.TestResponse();
}

public class testingClass
{
public string TestResponse()
{
return "hello world";
}
}
}


Related Topics



Leave a reply



Submit