I am trying to implement an example in youtube, the tutor got it right but I got an error.
I already have a private constructor and I cannot have public constructor in my code.
private static int _InstanceCount = 0;
private SingletonDemo1()
{
_InstanceCount++;
Console.WriteLine("Instance Count: " + _InstanceCount.ToString());
}
private static readonly Lazy<SingletonDemo1> _Instance = new Lazy<SingletonDemo1>();
public static SingletonDemo1 Instance
{
get
{
return _Instance.Value;
}
}
According to the example you need to manually initialize the object in the constructor of the Lazy just like in the demo video
private static readonly Lazy<SingletonDemo1> _Instance = new Lazy<SingletonDemo1>(() => new SingletonDemo1());
Note the factory function used.
Without it the code would try to use reflection to initialize the object but as you have already stated the constructor is private so it will fail. That is why you need to tell the Lazy
how to create the instance when needed.
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