M
Marcel Müller
I have seen two implementations to instantiate static objects:
#1 - the easy way
public static class Array<T>
{
public static readonly T[] Empty = new T[0];
}
#2 - using a get property
public static class Array<T>
{
private static T[] _Empty;
public static T[] Empty
{
get
{
if (_Empty == null)
_Empty = new T[0];
return _Empty;
}
}
}
The first implementation is the obvious one that I usually prefer.
But the I have seen the second form too. E.g. the Implementation of
Enumerable.Empty<T>() uses an internal helper class that works like #2.
Is there some serious reason to prefer #2?
The only things I can think of is that using the static class
initializer has side effects in case of exceptions and the existence of
a static class initializer involves locking while the second
implementation is lock free. (With some race condition that does not
harm with the .NET memory model.)
Marcel
#1 - the easy way
public static class Array<T>
{
public static readonly T[] Empty = new T[0];
}
#2 - using a get property
public static class Array<T>
{
private static T[] _Empty;
public static T[] Empty
{
get
{
if (_Empty == null)
_Empty = new T[0];
return _Empty;
}
}
}
The first implementation is the obvious one that I usually prefer.
But the I have seen the second form too. E.g. the Implementation of
Enumerable.Empty<T>() uses an internal helper class that works like #2.
Is there some serious reason to prefer #2?
The only things I can think of is that using the static class
initializer has side effects in case of exceptions and the existence of
a static class initializer involves locking while the second
implementation is lock free. (With some race condition that does not
harm with the .NET memory model.)
Marcel