Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I have a class and when I try to use it in another class I receive the error below.

using System; using System.Collections.Generic; using System.Linq;  namespace MySite {     public class Reminders     {         public Dictionary<TimeSpan, string> TimeSpanText { get; set; }          // We are setting the default values using the Costructor         public Reminders()         {             TimeSpanText.Add(TimeSpan.Zero, "None");             TimeSpanText.Add(new TimeSpan(0, 0, 5, 0), "5 minutes before");             TimeSpanText.Add(new TimeSpan(0, 0, 15, 0), "15 minutes before");             TimeSpanText.Add(new TimeSpan(0, 0, 30, 0), "30 minutes before");             TimeSpanText.Add(new TimeSpan(0, 1, 0, 0), "1 hour before");             TimeSpanText.Add(new TimeSpan(0, 2, 0, 0), "2 hours before");             TimeSpanText.Add(new TimeSpan(1, 0, 0, 0), "1 day before");             TimeSpanText.Add(new TimeSpan(2, 0, 0, 0), "2 day before");         }      } } 

Using the class in another class

class SomeOtherClass {       private Reminders reminder = new Reminders();     // error happens on this line:     private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];      .... 

Error (CS0236):

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

Why does it happen and how to fix it?

like image 235
GibboK Avatar asked Jan 21 '13 13:01

GibboK


People also ask

What is a field initializer?

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration. For more information, see Using Constructors. Note. A field initializer cannot refer to other instance fields.

Which method Cannot initialize non static members?

In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.


1 Answers

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.

like image 142
Oded Avatar answered Oct 09 '22 11:10

Oded