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?
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[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With