Ordering of static fields in C# matters

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.0 we now have the compound assignment!

public class Person
{
    private static EmptyPerson _emptyPerson;
    public static Person Empty => _emptyPerson ??= new EmptyPerson();
}

 

Advertisements
Posted in C#

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s