Hi Guys
Commenting out “if(instance == null)” is altering the otuput. Anyone knows please explain the reason.
Thank you
using System;
class Singleton
{
private static Singleton instance;
private static int numOfReference;
private string code;
private Singleton()
{
numOfReference = 0;
code = "Maasoom Faraz";
}
public static Singleton GetInstance()
{
//if (instance == null) Commenting out this will change the output
instance = new Singleton();
numOfReference++;
return instance;
}
public static int Reference
{
get { return numOfReference; }
}
public string Code
{
get { return code; }
set { code = value; }
}
}
public class SingletonClientCode
{
static void Main(string[] args)
{
//Singleton a = new Singleton();
//will result in error because constructor is private
Singleton b = Singleton.GetInstance();
Console.WriteLine(b.Code);
Console.WriteLine(Singleton.Reference);
Singleton c = Singleton.GetInstance();
Console.WriteLine(c.Code);
Console.WriteLine(Singleton.Reference);
c.Code = "Modified " + c.Code;
Singleton d = Singleton.GetInstance();
Console.WriteLine(d.Code);
Console.WriteLine(Singleton.Reference);
if (b == c && c == d && d == b)
Console.WriteLine("Instances are equal");
else
Console.WriteLine("Instances are not equal");
Console.ReadLine();
}
}
/*
Output
Maasoom Faraz
1
Maasoom Faraz
1
Maasoom Faraz
1
Instances are not equal
*/