Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created November 24, 2023 13:53
Show Gist options
  • Save sunmeat/a029e35f9598af4bfae27285091d959d to your computer and use it in GitHub Desktop.
Save sunmeat/a029e35f9598af4bfae27285091d959d to your computer and use it in GitHub Desktop.
singleton pattern C# example
class Singleton
{
private static Singleton instance;
private int value;
private Singleton()
{
value = 50;
}
public static Singleton GetInstance()
{
return instance ?? (instance = new Singleton());
}
public int GetValue()
{
return value;
}
public void SetValue(int value)
{
this.value = value;
}
}
class Program
{
static void Main()
{
var instance = Singleton.GetInstance();
Console.WriteLine(instance.GetValue());
instance.SetValue(75);
Console.WriteLine(instance.GetValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment