Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid Singleton in C# 6

Tags:

c#

.net

singleton

I was making this to implement a singleton pattern

private static ProcessDao _dao;
public static ProcessDao Dao
{
    get { return _dao ?? (_dao = new ProcessDao()); }
}

but in C# 6 auto properties has default values. Is this a correct implementation of singleton?

public static ProcessDao Dao { get; } = new ProcessDao();
like image 490
Nogro Avatar asked Nov 08 '22 23:11

Nogro


1 Answers

Is this a correct implementation of singleton?

Your first example is wrong in the sense that it isn't a thread-safe implementation of a singleton. If multiple threads called ProcessDao.Instance, you're likely to see different instances of the private field being created.

In contrary to that, your second example is thread-safe, as the compiler actually translates your auto-implemented getter only property to:

public class ProcessDao
{
    [CompilerGenerated]
    private static readonly ProcessDao <Dao>k__BackingField;
    public static ProcessDao Dao
    {
        [CompilerGenerated]
        get
        {
            return ProcessDao.<Dao>k__BackingField;
        }
    }
    static ProcessDao()
    {
        ProcessDao.<Dao>k__BackingField = new ProcessDao();
    }
}

The static constructor invocation is guaranteed by the runtime to at most once, so you're also getting the guarantee that this will not create multiple instances of the backing field.

Regarding laziness, that depends on the implementation of your ProcessDao class. The static constructor is guaranteed to run before the first reference of a static field in the class. If you have multiple static fields exposed, then the first will cause the invocation and the allocation of these objects. If you know you'll be using other static members and want maximum laziness, look into the Lazy<T> type introduced in .NET 4.0.

like image 186
Yuval Itzchakov Avatar answered Nov 15 '22 08:11

Yuval Itzchakov