A quick is this safe singleton question

P

PokerMan

I usually do singleton implementatios like this:

static readonly myClass instance = new myClass ();

public static myClass Instance
{
get { return instance; }
}

static myClass(){}

but in this situation my constructor has variables and making a static
constructor will not allow for these vars. So i am doing it like this:

static readonly myClass instance = new myClass ();

public static myClass Instance
{
get { return instance; }
}

private myClass ()
{
_someObj = new SomeClass();
_someObj .Completed += OnComplete;
}

I see no problem myself, as the statc instance is created, triggers the
constructor, initliaises the static instance and then i always ref the
static instance. So surely a static constructor is actually unneeded? I just
want to verify i am right in my assumption and there is not something abt a
signleton that i am unaware of.

Thanks
 
H

Hans Kesting

P

PokerMan

SO should i do this?:

static readonly myClass instance = new myClass ();

public static myClass Instance
{
get { return instance; }
}

myClass ()
{
_someObj = new SomeClass();
_someObj .Completed += OnComplete;
}

static myClass ()
{

}


Would that still call the code in my non static contructor?
 
G

Guest

The non static constructor is used to create an instance of the object. It
doesnt matter how you hold the instance, in a static or non static variable,
it is still an instance and is constructed by an instance constructor.

The static constructor is used to construct the type rather than an instance
of the type. The initialisation of the static field will be compiled into the
static constructor so you code will be

static readonly myClass instance;

public static myClass Instance
{
get { return instance; }
}

myClass ()
{
_someObj = new SomeClass();
_someObj .Completed += OnComplete;
}

static myClass ()
{
instance = new myClass ();
}


when compiled. The static constructor runs once per add domain the first
time a line is encountered that references the type in any way.
 
J

Jon Skeet [C# MVP]

PokerMan said:
SO should i do this?:

static readonly myClass instance = new myClass ();

public static myClass Instance
{
get { return instance; }
}

myClass ()
{
_someObj = new SomeClass();
_someObj .Completed += OnComplete;
}

static myClass ()
{

}


Would that still call the code in my non static contructor?

Yes - the only difference is how "lazy" it will be. If you don't really
mind if the instance is constructed a bit early, or in some situations
where you don't end up needing it, you can do without the static
constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top