Singleton Pattern in C#

Hi,
This piece of code will explain how to implement the Singleton pattern when we create a class.


public class MySingleTon
{
private static MySingleTon singleTonObject;
// private constructor. This will avoid creating object using new keyword
private MySingleTon()
{

}
// public method which will be called
public void GetName()
{
Console.WriteLine("Brainstorming Guy");
}
public static MySingleTon CreateInstance()
{
// this object will be used with lock, so that it will be always one thread which will be executing the code
object myObject = new object();
// put a lock on myObject. We won't be able to use singleTonObject becuase it will be null. lock is to make the object thread safe.
// lock can't be worked with null objects.
lock (myObject)
{
// check whether the instance was there. If it's not there, then create an instance.
if (singleTonObject == null)
singleTonObject = new MySingleTon();
}
return singleTonObject;
}
}

You can get an instance and you can make a call as given below.

MySingleTon myObject = MySingleTon.CreateInstance();
myObject.GetName();
myObject = MySingleTon.CreateInstance();
myObject.GetName();

When you execute the above piece of code, you can note that when the first time CreateInstance method is called, it will create an instance. But when you make a second call, it will check whether instance exists there and if it exists, it will return the same instance.
I placed comments in almost all the lines of the singleton class.
If you have any queries, please feel free to post it here.

Regards,
Brainstorming Guy aka Venkatarajan A


Comments

Author: Bunty27 Jun 2008 Member Level: Gold   Points : 2

Hi,

Really very nice piece of code on Singleton.

If possible give some theory related to singleton.

Keep posting such valuable codes.

Thanks for sharing your knowledge.

Thanks and Regards
S.S.Bajoria

Author: Shilpa Ginode27 Jun 2008 Member Level: Gold   Points : 2

Hi
Good Piece of code.

Design patterns is C# is always an headache for developer to understand.

i saw many sites on Design patterns but none of site in view is simple in explaining design patterns.

If you have implemented or understood about it.

Please share your knowledge with us.

Thanks
Shilpa

Author: Brainstorming Guy27 Jun 2008 Member Level: Gold   Points : 2

Thanks for your feedback.
Will post more code snippets on the design patterns in coming weeks.
Your feedback are always welcome.

Regards,
Brainstorming Guy aka Venkatarajan A

Author: pradipta17 Aug 2008 Member Level: Gold   Points : 2

The constructor should not be private.If you are doing so then you are restricting the class to be inherited.We can achieve the singleton pattern using static class too which is easier and you need not have to write so many lines of code but the disadvantage is static classes can't be inherited.I would like to suggest that the construtor should be protected instead of private.
Another thing also need to be done in the following code snippet.


lock (myObject) { // check whether the instance was there. If it's not there, then create an instance. if (singleTonObject == null) singleTonObject = new MySingleTon(); }

Before locking myObject ,singleTonObject should be checked for null values if it is null then myObject should be locked else it should not be locked.

Author: Brainstorming Guy19 Aug 2008 Member Level: Gold   Points : 1

Hi Pradipta,
I have one question here. If you are going to have a static class, why you need to create an instance of it? Can you explain me a bit on it.

Regards,
Brainstorming Guy aka Venkatarajan A
http://dotnetgurukul.blogspot.com

Author: pradipta19 Aug 2008 Member Level: Gold   Points : 2

Static class will work exactly the same way the singleton pattern implemented above.If you see the CreateInstance() method above its static and returns a static instance and as You have declared the constructor private then you can't neither create an instance nor you can inherit the class.So its same as static class(You can't create instance and can not inherit from static class).
Note:The static class is a new feature of .NET Framework 2.0 .It was not there in earlier verson of .NET Framework.

Please let me know in case any further clarifications

Author: Happy Coder19 Aug 2008 Member Level: Gold   Points : 2

BrainStorming Guy,

the static class or nothing but the singleton, they both acheive the common goal ensuring

1. the class has only one instance
No talk about instance in static class, but you hav a single copy in memory, so that's singleton

2. provide a global point of access to it.
static class are global, once loaded they stay in memory till the application stops.


AS pradipta said locking is mandatory, b'caz we are dealing with static methods here in your example.

Happy Coding !!!

The other way around is using a static instance of the class

Author: Happy Coder19 Aug 2008 Member Level: Gold   Points : 1

Simple definition for Singleton

Defines an Instance operation(CreateInstance method) that lets clients access its unique instance.
Instance is a class operation.

It's responsible for creating and maintaining its own unique instance.

Author: Happy Coder19 Aug 2008 Member Level: Gold   Points : 2

What problem does this solve ?

In all application, there is a need to have some common container from which to access global data and maintain some type of data.
There are also cases in object-oriented (OO) systems where there should be only one class, or a predefined number of instances of a class, running at any given time.
For example, when a class is being used to maintain an incremental counter, the simple counter class needs to keep track of an integer value that is being used in multiple areas of an application.
The class needs to be able to increment this counter as well as return the current value. For this situation, the desired class behavior would be to have exactly one instance of a class that maintains the integer and nothing more. That's where singleton comes in.

Author: Brainstorming Guy19 Aug 2008 Member Level: Gold   Points : 2

Hi Pradipta and Nagarjan,
Thanks for the explanation but there some advantages in Singleton over Static class.
1. Singleton is stateful and static classes or not.
2. SIngleton objects we can make thread safe but static classes we can't until unless it's not accessing the static members of its own.
3. If you are writing a code for utility, you can straight away you can implement the static class but if you are going to write your business logic, then it's always better to have a singletone.
Let me know whether my explanation is good enough on why singleton.

Regards,
Brainstorming Guy aka Venkatarajan A
http://dotnetgurukul.blogspot.com

Author: Happy Coder19 Aug 2008 Member Level: Gold   Points : 2

Although you can have a static class, the main issue here is whether methods of a static class are threadsafe, and they very much are.

The key thing to remember about "static" is that fields in a class marked static, or static methods of a class that deal with such fields, introduce a condition of non thread safety.
The method itself, as long as it does not deal with static fields in the class, is perfectly threadsafe.

Author: pradipta19 Aug 2008 Member Level: Gold   Points : 2

Yeah Nagarajan ,You are right static classes are very much thread safe.I also prefer using non-static class having a static instance to mimic singleton but I always make sure the constructor is protected and the class is eligible for inheritance, so that I can reuse the class.
I agree with Venkatrajan that static classes should be used for Utility functions.

Author: RishiRaj20 Aug 2008 Member Level: Gold   Points : 1

can you tell me any one, where we can implement this. give me an example from real time apps

Author: pradipta20 Aug 2008 Member Level: Gold   Points : 2

For Example You have an EmployeeCollection Class which contains the Employee Objects.The collection provides you methods to maintain employee objects(add/update/delete).When You need to add a new Employee then You have to get the EmployeeCollection instance then add the Employee to the collection.You can not create the EmployeeCollection instance each time you are add an Employee.Similarly to delete an employee you need to get the single instance of the EmployeeCollection and remove the employee from the collection.
Hope this will clarify your doubt.

Author: Brainstorming Guy20 Aug 2008 Member Level: Gold   Points : 2

Hi Nagarajan,
You are right. That's the thing i have mentioned in my second point
2. SIngleton objects we can make thread safe but static classes we can't until unless it's not accessing the static members of its own.

Regards,
Brainstorming Guy aka Venkatarajan A
http://dotnetgurukul.blogspot.com

Author: Raj10 Sep 2009 Member Level: Gold   Points : 0

Hi,

Good article. Good explanation.

Thanks,
Raj

Author: Sameer Sayani25 Sep 2009 Member Level: Gold   Points : 1

Good example Brainstorming Guy. Just 1 query, where do we need a singleton class? Can you give me some real world example?

Author: Sameer Sayani25 Sep 2009 Member Level: Gold   Points : 1

Good example Brainstorming Guy. Just 1 query, where do we need a singleton class? Can you give me some real world example?

Guest Author: vignesh17 Mar 2012

can you please say that employee program with coding?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: