A Field Initializer Cannot Reference the Nonstatic Field, Method, or Property

A field initializer cannot reference the nonstatic field, method, or property

This line:

private dynamic defaultReminder = 
reminder.TimeSpanText[TimeSpan.FromMinutes(15)];

You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException.

Instead, just use:

private dynamic defaultReminder = TimeSpan.FromMinutes(15);

Alternatively, set up the value in the constructor:

private dynamic defaultReminder;

public Reminders()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

There are more details about this compiler error on MSDN - Compiler Error CS0236.

c# - a field initializer cannot reference the nonstatic field method or property

You can implement it as Property that returns the computed string in its getter

namespace World
{
public class Human
{
// Personal traits
public string first_name;
public string last_name;
public string full_name { get { return first_name + " " + last_name}};
}
}

Is there a reason you use this way of writing member names? Normally I would do it like so:

namespace World
{
public class Human
{
// Personal traits
public string FirstName {get; set;}
public string LastName {get; set;}
public string FullName => $"{FirstName} {LastName}"; // C#7 notation notation
}
}

Public properties using PascalCasing, private ones camelCasing is "normal" according to MS and will even produce hints in VS2017

What does a field initializer cannot reference non static fields mean in C#?

Any object initializer used outside a constructor has to refer to static members, as the instance hasn't been constructed until the constructor is run, and direct variable initialization conceptually happens before any constructor is run. getUserName is an instance method, but the containing instance isn't available.

To fix it, try putting the usernameDict initializer inside a constructor.

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

What does it mean?

The error said:

A field initializer

It's referring to the field private LowLevelKeyboardProc _proc. It's a non-static field. The initializer part is = HookCallback;.

cannot reference the non-static field, method, or property 'HookCallback'

HookCallback is a non-static method, and the field initializer is obviously referring to it.

The thing that is forbidden here is instance members being initialized with other instance members. Since they are all initialized "at the same time" - when the instance is created - they should not refer to each other when being initialized.

It's something that the C# compiler could actually figure out in theory - the spec defines a specific order in which initializers run - but for whatever reason, the designers went with the error message instead.

How do you fix it?

It's only field initializers which aren't allowed to access instance members. You can access instance members in the constructor, which runs right after the field initializers. So, just move the initialization to your constructor (as recommended by Microsoft):

private LowLevelKeyboardProc _proc;

public ScreenShotConfigurationForm()
{
InitializeComponent();
_proc = HookCallback;
}

A field initializer cannot reference the non-static field, method, or property 'MyController._config'

Change your field to be a property instead, like this:

public string apiURL => _config.GetValue<string>("ServiceURL");

When using = you are creating a field.

When using => you are creating a get-only property.

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

you have to move a method call to the constructor

 class LevelManager
{
public LvlData CurrentLevelData {get; set;}

public LevelManager()
{
CurrentLevelData = readLvl("../Level/Def/lvl.txt");
}

or make the method and property static, but it doesn't make much sense

public static LvlData CurrentLevelData {get; set; } = readLvl("../Level/Def/lvl.txt");

public static LvlData readLvl(string dir)
{
.....
}

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";
}
}
}

A field initializer cannot reference the non-static field, method, or property 'SignalServer.connectionString' (CS0236)

Your problem is this line:

SqlDependencyEx sqlDependency = new SqlDependencyEx(connectionString);

Move it inside the constructor instead:

SqlDependencyEx sqlDependency;
public SignalServer(TestController testController, IConfiguration configuration)
{
Configuration = configuration;
_testController = testController;
connectionString = Configuration.GetConnectionString("DefaultConnection");
//Put it here
sqlDependency = new SqlDependencyEx(connectionString);
}

I don't know much about your design but you probably don't even need to save the connection string in the connectionString field. You might be able to just use it directly from the call to the Configuration.GetConnectionString method or the reference to the Configuration object you are storing.



Related Topics



Leave a reply



Submit