Below are two different ways to initialize static readonly fields. Is there a difference between the two approaches? If yes, when should one be preferred over the other?
class A
{
private static readonly string connectionString =
WebConfigurationManager.ConnectionStrings["SomeConnection"].ConnectionString;
}
class B
{
private static readonly string connectionString;
static B()
{
connectionString =
WebConfigurationManager.ConnectionStrings["SomeConnection"].ConnectionString;
}
}
There is one subtle difference between these two, which can be seen in the IL code – putting an explicit static constructor tells the C# compiler not to mark the type as beforefieldinit. The beforefieldinit affects when the type initializer is run and knowing about this is useful when writing lazy singletons in C#, for example.
In brief the difference is this:
In all other aspects they are the same. Output from Reflector:
Class A:
Class B: