Using static fields in a class

So, I have a field in the class, but for some reason it returns with an uninitialized value of 01.01.01.01.

private static DateTime start = new DateTime(2011, 1, 1); 

Another static method used as an initializer in another field.

  private static readonly DateTime[] dates = SetupDates(20 * 12); private static DateTime[] SetupDates(int n){ var d = start; .... } 

I thought that the β€œnew” at the beginning would need to be completed before SetupDates could continue ... so the local variable d would contain 2011.1.1. It seems like I'm wrong and I should use a static constructor instead. Is this behavior expected?

+4
source share
5 answers

The order is here .

The initializers of a static variable of a class field correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

Make sure the static start field is declared first. Or even better, use a static constructor so that you do not rely on the order of the fields.

For example, this works:

  private static DateTime start = new DateTime(2011, 1, 1); private static readonly DateTime[] dates = SetupDates(20 * 12); 

But it is not

  //Bad SetupDates relies on start which is not initialized private static readonly DateTime[] dates = SetupDates(20 * 12); private static DateTime start = new DateTime(2011, 1, 1); 

Assuming you changed SetupDates to return DateTime[]

+6
source

Just move all the Init code into a static constructor and execute it in the order you want to execute. Case is closed;)

+2
source

There are no static fields initialized before calling SetupDates() , there is something else in your code that is not visible from the code really provided.

For example, I see an ad:

 private void SetupDates(int n) 

but also

 private static readonly DateTime[] dates = SetupDates(20 * 12); 

EDIT

If SetupDates() intializaes is a static field, as in the provided code (but I am not repeating the code as it is), you should pay attention to the order of initialization. In that case may occur when SetupDates() is called before start intialized.

The function returns nothing, it is impossible even to compile it.

+1
source

You cannot call the SetupDates instance SetupDates to construct a static dates field. This code should not compile.

+1
source

I don’t understand that you are asking a question, can you send only the part of the code that causes the problems? The above code does not compile. You can initialize a static field with a new object.

  var test = new Test(); test.SetupDates(); 

If you put a breakpoint in the SetupDates method, the date will be 1/1/2011

  public class Test { private static DateTime start = new DateTime(2011, 1, 1); public void SetupDates() { //breakpoint here var d = start; } } 
0
source

Source: https://habr.com/ru/post/1393138/


All Articles