Take a look at the
Lazy<T> Class[
^] - it provides an implementation of the singleton pattern.
Your implementation contains a small bug - you need to make getInstance() static too. The will enable you to get the single instance of OnlyOne using
OnlyOne obj = OnlyOne::getInstance();
private static OnlyOne instance = null;
private OnlyOne()
{
}
public static OnlyOne getInstance()
{
if(instance==null)
{
instance = new OnlyOne();
}
return instance;
}
From the
documentation[
^]:
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types.
Regards
Espen Harlinn