Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Singleton SingletonObject = Singleton.GetObject();
SingletonObject.Print("How World");
//Here created the new object and print the value
Singleton SingletonObject1 = Singleton.GetObject();
SingletonObject1.Print("Hi World");
//Here using the existing object and print the value
Singleton SingletonObject2 = Singleton.GetObject();
SingletonObject2.Print("Code World");
//Here using the existing object and print the value
Console.ReadLine();
}
}
public class Singleton
{
protected static Singleton _obj ;
private Singleton()
{
}
public static Singleton GetObject()
{
if (_obj == null)
{
Console.WriteLine(5);
//First time print the value
_obj = new Singleton();
//Here object created for first time only, when _obj value is null, if _obj is not null then it's using the same object with out creating new one(Object)
}
if (_obj != null)
{
Console.WriteLine(10);
//Rest of time using same object and here _obj value is not null, So it's print the value first too
}
return _obj;
}
public void Print(string s)
{
Console.WriteLine(s);
}
}
}
Advertisements
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.
AcceptLearn more