via Ordering of static fields in C# matters
The ordering of static fields does matter.
But per your examples, here is the pattern I always use:
public class Person { private static EmptyPerson _emptyPerson; public static Person Empty => _emptyPerson ?? ( _emptyPerson = new EmptyPerson() ); }
The allows the Empty
value to be initialized once and read-only, yet still used many times.
It also hides away the requirements of the initialization (the value pulled from a database for example) from the public getter. We could even put the value into a Lazy<Person>()
.
And in C# 8 we now have the compound assignment!
public class Person { private static EmptyPerson _emptyPerson; public static Person Empty => _emptyPerson ??= new EmptyPerson(); }