Click to See Complete Forum and Search --> : singleton classes in c#?


some1nu
October 23rd, 2001, 10:31 PM
is there a c# equivalent of a singleton class? if so, how do i go about creating one? thanks!

Arild Fines
October 24th, 2001, 11:50 AM
Something like this might do the trick:

public class MySingleton
{
private static MySingleton instance;

//static ctor - just gotta love these
static MySingleton()
{
instance = new MySingleton();
}

//private ctor to avoid direct instantiation
private MySingleton()
{
//do stuff here
}

//returns the only instance of this object
public MySingleton GetInstance()
{
return instance;
}
}





"A society without religion is like a crazed psychopath without a loaded .45"

some1nu
October 24th, 2001, 08:22 PM
so, to "instantiate" the class, i do something like this?


MySingleton singleton = MySingleton.GetInstance();

Arild Fines
October 24th, 2001, 08:26 PM
Exactly.

"A society without religion is like a crazed psychopath without a loaded .45"