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
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 '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)
{
.....
}
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
The correct syntax should be:
int count, xmin, xmax, ymin, ymax = 0;
EDIT:
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://docs.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, method or property in EventHandler
The error message says exactly what the problem is - your field initializer is using an instance member (FilesFound
), via the lambda expression. You can't refer to other instance members within instance field initializers.
The simple fix is to move the initialization to the constructor:
private EventHandler<FileFoundArgs> onFileFound;
public FileSearcher()
{
onFileFound = (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.FoundFile);
FilesFound = FilesFound + 1;
};
FileFound += onFileFound;
}
Or if you're not going to use onFileFound
anywhere else, get rid of it as a field entirely, and just subscribe directly to the event in the constructor:
private EventHandler<FileFoundArgs> onFileFound;
public FileSearcher()
{
FileFound += (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.FoundFile);
FilesFound = FilesFound + 1;
};
}
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.
Related Topics
C# Open a New Form Then Close the Current Form
How to Make an Event in the Usercontrol and Have It Handled in the Main Form
"A Project with an Output Type of Class Library Cannot Be Started Directly"
What Is [Serializable] and When Should I Use It
C# Member Variable Initialization; Best Practice
Handling Warning for Possible Multiple Enumeration of Ienumerable
Deserializing JSON Object Array with JSON.Net
Switch Statement Fallthrough in C#
Difference Between Events and Delegates and Its Respective Applications
How to Send Emails Through Ssl Smtp with the .Net Framework
How to Use Webrequest to Access an Ssl Encrypted Site Using Https
What Is the Purpose of Self Tracking Entities
What Does the '=>' Syntax in C# Mean
How to Set a Property Value with Reflection
Custom Text Color in C# Console Application