Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using static fields in a class

Tags:

c#

.net

.net-4.0

So I have a field in a class, but for some reason it is comming back with an uninitialised value of 0001.01.01.

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

There's 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 "new" in start would need to be completed before before SetupDates could continue... so local variable d would contain 2011.1.1. Looks like I'm mistaken, and I should use a static constructor instead. Is this behaviour to be expected?

like image 740
sgtz Avatar asked Dec 27 '22 07:12

sgtz


1 Answers

The order matters here.

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

Make sure your start static field is declared first. Or better yet use a static constructor so you're not relying on the order of fields.

For example this works:

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

But this doesn't

    //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 change SetupDates to return a DateTime[]

like image 198
Ray Avatar answered Jan 15 '23 07:01

Ray