Singleton Pattern in CSharp
Level Author
Beginner Kunal Cheda
Singleton assures that there is one and only one instance of the class and provides a global point of access to it.There are number of cases in programming where you need to make sure that there can be one and only one instance of a class e.g Window Manager,Print Spooler etc.
Points to Note in the Example Constructor of Class B is private not allowing other classes to Create the Instance. Class B has a private static variable(x) which will have the one and one Instance of the Class B, and can be accessed through Static method GetB. If GetB is accessed for the first time x will be null ,and will create the Instance and return x, from next requests to GetB method it will simply return x.
Save the file as Singleton.cs, Compile C:\>csc Singleton.cs and Run C:\>Singleton
CODE
Singleton.cs
using System;
class A
{
public static void Main(String [] args)
{
B m = B.GetB();
m.j=100; //make changes to instance variable j
Console.WriteLine(m.j);
B x = B.GetB();
//x.j print's 100 which means that there is one and only one Instance
Console.WriteLine(x.j);
}
}
class B
{
private static B x;
public int j= 0;
private B()
{
}
public static B GetB()
{
if(x==null)
{
x=new B();
}
return x;
}
}