Before you start

What to expect

Singleton

What is a Singleton?

Why Singleton?

Lets make one

1:    public class ConnectionManager  
2: {
3: public ConnectionManager()
4: {
5: //Some initialization
6: }
7: }
1:    public class ConnectionManager  
2: {
3: private ConnectionManager()
4: {
5: //Some initialization
6: }
7: }
1:    public class ConnectionManager  
2: {
3: public static ConnectionManager Instance = new ConnectionManager();
4: private ConnectionManager()
5: {
6: //Some initialization
7: }
8: }
1:   public class ConnectionManager  
2: {
3: private static ConnectionManager Instance;
4: private ConnectionManager()
5: {
6: //Some initialization
7: }
8: public static ConnectionManager GetInstance()
9: {
10: if (Instance==null)
11: {
12: Instance=new ConnectionManager();
13: }
14: return Instance;
15: }
16: }

BUT WAIT

1:   public static ConnectionManager GetInstance()  
2: {
3: return Instance ?? (Instance = new ConnectionManager());
4: }

It can be even better

1:    public class ConnectionManager  
2: {
3: private static ConnectionManager _singleton;
4: public static ConnectionManager Instance => _singleton ?? (_singleton = new ConnectionManager());
5: private ConnectionManager()
6: {
7: //Some initialization
8: }
9: }

Author — “How to Make A Game” / Apress, Springer Nature | Head Of Unity Department at Brain Station 23 Limited | Co-Founder of Capawcino Cat Cafe