Is this a valid Singleton in C # 6

I did this to implement a singleton pattern

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

but the C # 6 properties automatically specify default values. Is this the correct singleton implementation?

public static ProcessDao Dao { get; } = new ProcessDao();
+4
source share
1 answer

Is this the correct singleton implementation?

Your first example is incorrect in the sense that it is not a thread safe implementation of singleton. If there are multiple threads called ProcessDao.Instance, you are likely to see different instances of the private field being created.

In contrast, your second example is thread safe, as the compiler actually only translates your automatically implemented getter property:

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();
    }
}

, , .

, ProcessDao. . , . , , Lazy<T>, .NET 4.0.

+1

Source: https://habr.com/ru/post/1621317/


All Articles