C# is a multi-paradigm programming language. But it started as an object oriented programming language (originally based on Java), and the OOP is still the most important trait of C#.
Singleton Design Pattern in C#
Singleton.cs
namespace CodeAndTips;
public sealed class Singleton
{
private static volatile Singleton? _instance;
private static readonly object _lock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if(_instance == null) {
lock (_lock) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
}
public string Name { get; set; } = "Nobody";
}
Program.cs
using CodeAndTips;
var instance = Singleton.Instance;
instance.Name = "Joe";
Console.WriteLine($"Hello, {instance.Name}!");