Last active
January 15, 2026 22:03
-
-
Save sunmeat/cd4089b8a3812804d39317251fad7a91 to your computer and use it in GitHub Desktop.
singleton classic C# example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace SingletonExample | |
| { | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| Singleton obj = Singleton.GetInstance(); | |
| Console.WriteLine(obj.GetValue()); | |
| obj.SetValue(75); | |
| Console.WriteLine(obj.GetValue()); | |
| } | |
| } | |
| public class Singleton | |
| { | |
| private static Singleton? instance = null; | |
| private int value; | |
| private Singleton() | |
| { | |
| value = 50; | |
| } | |
| public static Singleton GetInstance() | |
| { | |
| if (instance == null) | |
| { | |
| instance = new Singleton(); | |
| } | |
| return instance; | |
| } | |
| public int GetValue() | |
| { | |
| return value; | |
| } | |
| public void SetValue(int value) | |
| { | |
| this.value = value; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment