Singleton implementation

  • Thread starter Thread starter Daniel
  • Start date Start date
D

Daniel

Hey guys

I implement my singleton by doin this at the top of the class.

public static readonly DrawDetails Instance = new DrawDetails();

Then to access the instance i do DrawDetails.Instance.SomeMethod();

My query is, everytime i call that line does it call the constructor again?
Or is the constructor called once, the first time i use it and from then on
it just reuses it without calling the constructor.

I presume it doesnt keep calling it as i made it static but i just want to
be sure.

Thanks.
 
Daniel,

The constructor is called just once, the first time the type is
referenced.
 
For a singleton, you hide/private the default constructor.



There should be one static method (usually people call it .GetInstance() )
to return your object.

I have a singleton example at:

http://spaces.msn.com/sholliday/ 12/1/2005 entry

Download the code (near the bottom of the entry)
and look at the code in InMemoryObjectHolder.cs


...
 
Hello Daniel,

Take into account that pure .net singleton is not an easy task, because CLR
create a copy of static members for each application
domain

You realization is just an application singleton

D> Hey guys
D> I implement my singleton by doin this at the top of the class.
D> public static readonly DrawDetails Instance = new DrawDetails();
D> Then to access the instance i do DrawDetails.Instance.SomeMethod();
D> My query is, everytime i call that line does it call the constructor
D> again? Or is the constructor called once, the first time i use it and
D> from then on it just reuses it without calling the constructor.
D> I presume it doesnt keep calling it as i made it static but i just
D> want to be sure.

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
sloan said:
For a singleton, you hide/private the default constructor.

There should be one static method (usually people call it .GetInstance() )
to return your object.

I have a singleton example at:

http://spaces.msn.com/sholliday/ 12/1/2005 entry

Download the code (near the bottom of the entry)
and look at the code in InMemoryObjectHolder.cs

It's not thread-safe, unfortunately.

See http://www.pobox.com/~skeet/csharp/singleton.html

By the way, do you realise that the

if (constant == variable)

idiom used in C/C++ to avoid accidental assignment instead of
comparison is unnecessary in C#? I believe most people find

if (variable == constant)

easier to read (I know I do).
 
Back
Top