From MSDN
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced
Now came to my problem:
public static class DateFormat
{
private static List<string> DateFormats = new List<string>();
public static string DateSeparator { get; set; } = "/";
public static string Current { get; set; } = DateFormats[1]; // error here
static DateFormat()
{
DateFormats.Add("yyyy{0}MM{0}dd HH{1}mm{1}ss");
DateFormats.Add("yyyy{0}MM{0}dd hh{1}mm{1}ss");
}
}
As you see above when calling DateFormats[1] error
"The type initializer for 'DateFormat' threw an exception."
Is constructor should calling static constructor first? so that dictionary will filled then any call to variable which use it will be ok.
This behaviour is documented here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Specifically, this section:
Since static field variable initializers are indeed present, they will be initialised BEFORE the static constructor, which is why you are seeing that error:
will be executed before
and thus of course, the
DateFormatslist is still empty at the point thatDateFormats[1]is executed.To solve this, just initialise
Currentin the static constructor: