I would like to get an instance of a static class, but I can’t seem to do this without implementing a singleton wrapper on a non-static class– is this possible, or am I missing something?
public class MyInstanceTester
{
public MyInstanceTester()
{
//this is how i get a reference to a singleton now
MyClass instance1 = MyClass.Instance();
//this is what is would like to do (if only the compiler would let me)
MyStaticClass instance2 = MyStaticClass.Instance();
}
}
public class MyClass
{
private static MyClass _myInstance;
static MyClass()
{
_myInstance = new MyClass();
}
public static MyClass Instance()
{
return _myInstance;
}
}
public static class MyStaticClass
{
public static MyStaticClass Instance
{
get
{
return this;
}
}
}
There is no such thing as an instance of a static class. The singleton pattern simply returns the same instance of a class to repeated requests.
You may be getting confused by:
This simply means that there will be a single instance of that particular object among all objects instantiated of the type that have _myInstance as a member.
A few notes:
thiskeyword is not valid in a static memberthiswill never be validFurther reading: Jon Skeet has an excellent write up on implemeting Singletons in C# In Depth. I would suggest reading and studying this article until you grok it. It is quite good.