Qus:    How can we implement singleton design pattern in C#?
Nov 24, 2020 14:19 2 Answers Views: 94 NAIDU

 Please have a look at below example -



namespace SingletonDemo

{

public sealed class Singleton

{

private static int counter = 0;

private static Singleton instance = null;

public static Singleton GetInstance

{

get

{

if (instance == null)

instance = new Singleton();

return instance;

}

}



private Singleton()

{

counter++;

Console.WriteLine("Counter Value " + counter.ToString());

}

public void PrintDetails(string message)

{

Console.WriteLine(message);

}

}

}

Prev Next
Answers (2)
PARTH Nov 25, 2020 08:07
Answer:   Please have a look at below example -

namespace SingletonDemo
{
public sealed class Singleton
{
private static int counter = 0;
private static Singleton instance = null;
public static Singleton GetInstance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}

private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
}

DIVYA Nov 25, 2020 08:14
Answer:   In The singleton design pattern, only one Instance of a class will be created and will be used to provide access point globally
Below code will demonstrate the Singleton Design Pattern in C#
public sealed class Singleton
{
private static readonly Singleton obj = new Singleton();
}

Post Your Answer
Guest User

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect