Search⌘ K
AI Features

Singleton: Implementation and Example

Explore how to implement the Singleton design pattern in C# by creating a static instance and managing object creation. Learn to ensure a single shared instance throughout your application with a hands-on console app example.

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:

C#
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;
}
}
...