By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,997 Members | 1,270 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,997 IT Pros & Developers. It's quick & easy.

Diff. between singleton class and static class

P: n/a
DBA
Hi All,

What is the diff. between a singleton class and a static class in C#?
Nov 17 '05 #1
Share this Question
Share on Google+
15 Replies


P: n/a
KH
A static class does not allow an instance of itself to be created by anything
other than itself - it has no public ctors:

class T
{
private T() { }

public static T Get() { return new T(); }
};

T t1 = new T(); // Error, no public constructor
T t2 = T.Get(); // Ok
T t3 = T.Get(); // Ok; returns another instance of T

A singleton allows only one instance of the class to ever be created:

class S
{
private S() { }

private static S instance = new S();

public static S Get() { return S.instance; }
};

S s1 = new S(); // Error, no public constructor
S s2 = S.Get(); // Ok; always returns the same instnace
S s3 = S.Get(); // Ok; returns the same instance as s2


"DBA" wrote:
Hi All,

What is the diff. between a singleton class and a static class in C#?

Nov 17 '05 #2

P: n/a
DBA <DB*@discussions.microsoft.com> wrote:
What is the diff. between a singleton class and a static class in C#?


A singleton allows access to a single created instance - that instance
(or rather, a reference to that instance) can be passed as a parameter
to other methods, and treated as a normal object.

A static class allows only static methods.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3

P: n/a
Hi,

first the currently there is no a way to declare a class static, you do it
implicitely by declaring static all the members of it. The members will
exist as long as the Appdomain does.

A singleton is a "normal" class with the only difference that the
constructor is private, hence the only way to "create" an instance is using
the property/method that return the instance. If needed you can also declare
a method that dispose the instance, so it can be recreated again when
needed.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"DBA" <DB*@discussions.microsoft.com> wrote in message
news:D4**********************************@microsof t.com...
Hi All,

What is the diff. between a singleton class and a static class in C#?

Nov 17 '05 #4

P: n/a
Ignacio,

The statement:
first the currently there is no a way to declare a class static
Is not true. In the current beta release of C# 2.0, there is support
for static classes, where all of the members must be static (and the
compiler issues a warning if any of the members are not).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us> wrote
in message news:uI**************@TK2MSFTNGP15.phx.gbl... Hi,

first the currently there is no a way to declare a class static, you do it
implicitely by declaring static all the members of it. The members will
exist as long as the Appdomain does.

A singleton is a "normal" class with the only difference that the
constructor is private, hence the only way to "create" an instance is
using the property/method that return the instance. If needed you can also
declare a method that dispose the instance, so it can be recreated again
when needed.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"DBA" <DB*@discussions.microsoft.com> wrote in message
news:D4**********************************@microsof t.com...
Hi All,

What is the diff. between a singleton class and a static class in C#?


Nov 17 '05 #5

P: n/a
You can declare the entire class as static in VB. I believe the next version
of C# will also have that ability, but I'm not certain.

The only reasons (that I know) to use a singleton is if you need to pass it
to a function call. For example, an IComparer class.
--
Jonathan Allen
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us> wrote
in message news:uI**************@TK2MSFTNGP15.phx.gbl...
Hi,

first the currently there is no a way to declare a class static, you do it
implicitely by declaring static all the members of it. The members will
exist as long as the Appdomain does.

A singleton is a "normal" class with the only difference that the
constructor is private, hence the only way to "create" an instance is
using the property/method that return the instance. If needed you can also
declare a method that dispose the instance, so it can be recreated again
when needed.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"DBA" <DB*@discussions.microsoft.com> wrote in message
news:D4**********************************@microsof t.com...
Hi All,

What is the diff. between a singleton class and a static class in C#?


Nov 17 '05 #6

P: n/a
Hi,

Yes, I meant that , just that I totally miswrote that sentence :)

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:er**************@TK2MSFTNGP14.phx.gbl...
Ignacio,

The statement:
first the currently there is no a way to declare a class static


Is not true. In the current beta release of C# 2.0, there is support
for static classes, where all of the members must be static (and the
compiler issues a warning if any of the members are not).

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us>
wrote in message news:uI**************@TK2MSFTNGP15.phx.gbl...
Hi,

first the currently there is no a way to declare a class static, you do
it implicitely by declaring static all the members of it. The members
will exist as long as the Appdomain does.

A singleton is a "normal" class with the only difference that the
constructor is private, hence the only way to "create" an instance is
using the property/method that return the instance. If needed you can
also declare a method that dispose the instance, so it can be recreated
again when needed.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"DBA" <DB*@discussions.microsoft.com> wrote in message
news:D4**********************************@microsof t.com...
Hi All,

What is the diff. between a singleton class and a static class in C#?



Nov 17 '05 #7

P: n/a
DBA
KH, Jon Thank you for responses. One more question:
When to use a singleton class and when to use a staic class? I think both
has the same functionality

"Jon Skeet [C# MVP]" wrote:
DBA <DB*@discussions.microsoft.com> wrote:
What is the diff. between a singleton class and a static class in C#?


A singleton allows access to a single created instance - that instance
(or rather, a reference to that instance) can be passed as a parameter
to other methods, and treated as a normal object.

A static class allows only static methods.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #8

P: n/a
mdb
=?Utf-8?B?REJB?= <DB*@discussions.microsoft.com> wrote in
news:BE**********************************@microsof t.com:
KH, Jon Thank you for responses. One more question:
When to use a singleton class and when to use a staic class? I think
both has the same functionality


For one example, whenever you want to be able to pass the instance of the
class as a parameter to a function... Just because you have a
"singleton" class doesn't mean that there's only one singleton class
(although by definition there's only one instance of *each* of them)...
Such as...

public interface IWorkInterface
{
void DoSomeWork();
}

public SingletonA : IWorkInterface
{
.... singleton implementation ...
public void DoSomeWork() { ... }
}

public SingletonB : IWorkInterface
{
.... singleton implementation ...
public void DoSomeWork() { ... }
}

public void StartWork(IWorkInterface iwi)
{
iwi.DoSomeWork();
}

public void Main()
{
IWorkInterface singletonA = new SingletonA();
IWorkInterface singletonB = new SingletonB();

// here i'm passing the object - its a singleton
StartWork(singletonA);

// here i'm passing a different singleton
StartWork(singletonB);
}

--
-mdb
Nov 17 '05 #9

P: n/a

First, the Singleton Pattern generally creates a single instance of a
class, but
this is not absolute. In fact, you can argue that some of the
flexibility of the
Singleton Pattern is that it allows you the programmer to return more
than
one instance of a class at a later date without breaking the client
code. The
classic example is an expensive hardware resource. You implement this as
a
Singleton Pattern. Later, when you win the lottery you can purchase a
second
unit of this expensive hardware resource and recode the class factory to
return one of the two hardware controllers using load sharing. The
caller does
not know that there are now two units.

Perhaps it would help to think of where the code goes and how this could
help you understand the difference between static methods and fields and
a
Singleton Pattern.

In a Static call you have one set of static methods and fields in
memory. There
is no need for a pointer to the instance stack frame. Now let's go back
to the
classic Singleton where you have one instance of the class. Although the
code
for instance methods _appears_ to be copied for each instance so that
each
instance has BEHAVIOR, in reality the code for instance methods is
_shared_!
So the only real difference between Static calls and instance calls is
that
instance calls act on instance data and each instance has its own
separate
data in memory. But if you only have one instance then there is only one
copy
of instance data. SO, the only real difference between Static and a
single
instance is that there is a pointer to this to access the instance data.

There _are_ advantages to the Singleton pattern and they include:

1) Adds a level of indirection. This allows the creation of more than
one
instance of the class at a later date without breaking client code.
2) Encapsulates data and methods into a separate namespace, the
singleton
class.
3) Allows sub-classing.
4) Provides access control to the single instance.

Hope that helps.

Have fun storming the castle,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #10

P: n/a
Jeff Louie <je********@yahoo.com> wrote:
First, the Singleton Pattern generally creates a single instance of a
class, but this is not absolute. In fact, you can argue that some of
the flexibility of the Singleton Pattern is that it allows you the
programmer to return more than one instance of a class at a later
date without breaking the client code.
I'd argue that in that case it's a factory. Certainly the GoF book
defines a singleton in terms of only providing one instance. I agree
that using a singleton allows you to change it into a factory at a
later date without breaking client code though. (Assuming the client
code isn't relying on it being a singleton.)

<snip>
There _are_ advantages to the Singleton pattern and they include:
<snip>
3) Allows sub-classing.


It allows the singleton to be a subclass of something else. The normal
patterns that ensure that only a single instance is ever created don't
work well with subclasses. It can be done, but it's somewhat messy.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #11

P: n/a
Hi,
3) Allows sub-classing.


It allows the singleton to be a subclass of something else. The normal
patterns that ensure that only a single instance is ever created don't
work well with subclasses. It can be done, but it's somewhat messy.


Why messy?

It's the member who return the instance the one in charge of that, it could
work as a factory deciding at runtime an instance of what class to create
and return. Somewhere I saw a code like this:

public static SingletonClass GetInstance()
{
if ( instance == null )
{
//decide which class derived of SingletonClass to instantiate
return instance
}
}

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Nov 17 '05 #12

P: n/a
Hi,

Also there is the fact that you can control when to create the singleton,
even so you can create the singleton more than one time during the lifetime
of the app. The only thing that the singleton assure is that only one
instance exist at a given time, not that the same instance exist always.

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"mdb" <m_b_r_a_y@c_t_i_u_s_a__d0t__com> wrote in message
news:Xn****************************@207.46.248.16. ..
=?Utf-8?B?REJB?= <DB*@discussions.microsoft.com> wrote in
news:BE**********************************@microsof t.com:
KH, Jon Thank you for responses. One more question:
When to use a singleton class and when to use a staic class? I think
both has the same functionality


For one example, whenever you want to be able to pass the instance of the
class as a parameter to a function... Just because you have a
"singleton" class doesn't mean that there's only one singleton class
(although by definition there's only one instance of *each* of them)...
Such as...

public interface IWorkInterface
{
void DoSomeWork();
}

public SingletonA : IWorkInterface
{
... singleton implementation ...
public void DoSomeWork() { ... }
}

public SingletonB : IWorkInterface
{
... singleton implementation ...
public void DoSomeWork() { ... }
}

public void StartWork(IWorkInterface iwi)
{
iwi.DoSomeWork();
}

public void Main()
{
IWorkInterface singletonA = new SingletonA();
IWorkInterface singletonB = new SingletonB();

// here i'm passing the object - its a singleton
StartWork(singletonA);

// here i'm passing a different singleton
StartWork(singletonB);
}

--
-mdb

Nov 17 '05 #13

P: n/a
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us>> wrote:
3) Allows sub-classing.


It allows the singleton to be a subclass of something else. The normal
patterns that ensure that only a single instance is ever created don't
work well with subclasses. It can be done, but it's somewhat messy.


Why messy?

It's the member who return the instance the one in charge of that, it could
work as a factory deciding at runtime an instance of what class to create
and return. Somewhere I saw a code like this:

public static SingletonClass GetInstance()
{
if ( instance == null )
{
//decide which class derived of SingletonClass to instantiate
return instance
}
}


In that case though, there's nothing to stop the derived class from
creating an instance of itself - or another derived class to derive
from the SingletonClass.

One of the benefits of the singleton pattern in its normal form is that
you can guarantee that the only thing that will create an instance of
the class is the class itself, because it only has a private
constructor. (Leaving reflection aside, of course.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #14

P: n/a
Hi John.. In line.
Certainly the GoF book defines a singleton in terms of only providing one
instance.<

That is the "Intent", but one of the "Consequences" is "4. Permits a
variable
number of instances." GoF pp 128.
It allows the singleton to be a subclass of something else. The normal

patterns that ensure that only a single instance is ever created don't
work well with subclasses. It can be done, but it's somewhat messy.<

Hmm. I don't understand why this is messy. In C# an interface can be
looked
at as subclassing where a concrete class implements an interface or
extends a
pure virtual class. The singleton GetInstance method can return an
interface
type or a method can take a singleton reference of an interface type
allowing
you to program to an interface. The supplier supplies a single instance
of an
object that implements the contract, the interface.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #15

P: n/a
Jeff Louie <je********@yahoo.com> wrote:
It allows the singleton to be a subclass of something else. The normal

patterns that ensure that only a single instance is ever created don't
work well with subclasses. It can be done, but it's somewhat messy.<

Hmm. I don't understand why this is messy. In C# an interface can be
looked at as subclassing where a concrete class implements an
interface or extends a pure virtual class. The singleton GetInstance
method can return an interface type or a method can take a singleton
reference of an interface type allowing you to program to an
interface. The supplier supplies a single instance of an object that
implements the contract, the interface.


See my reply to Ignacio - the normal singleton pattern is very elegant
in enforcing a single instance without ever having to actually check in
a constructor that it hasn't been constructed before, etc. With
subclassing some of that elegance goes away.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #16

This discussion thread is closed

Replies have been disabled for this discussion.