...

/

Singleton: Implementation and Example

Singleton: Implementation and Example

Learn the Singleton design pattern by implementing an example program.

We'll cover the following...

Implementing the Singleton design pattern

We’ll create a .NET console application and add a Singleton class to it. For this purpose, we will add the SingletonObject.cs file with the following content:

Press + to interact
namespace Singleton_Demo;
internal class SingletonObject
{
private static SingletonObject? instance;
public static SingletonObject GetInstance()
{
if (instance is null)
{
var random = new Random();
instance = new SingletonObject(random.Next());
}
return instance;
}
private SingletonObject(int data)
{
Data = data;
}
public int Data
{
get; private set;
}
}
...