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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With