Reputation: 1930
I would like to write a base class which implements the basic structure of a lazy static pattern.
public class LazyStatic<T>
{
private static T _static;
public static T Static
{
get
{
if (_static == null) _static = Activator.CreateInstance<T>();
return _static;
}
}
}
Once I am done with this base class, I would use it like
public class MyOtherClass : LazyStatic<MyOtherClass>
{
...
}
Is the base class correctly implemented?
Upvotes: 0
Views: 104
Reputation: 45135
You are assuming that T
has a parameterless constructor, but you don't restrict you generic class so that the compiler knows that:
public class LazyStatic<T> where T : new()
{
private static T _static;
public static T Static
{
get
{
if (_static == null) _static = new T();
return _static;
}
}
}
Upvotes: 1