C# Singleton implement
1
// Singleton
2
using System;
3![]()
4
public class Singleton
5
{
6
private static Singleton instance;
7![]()
8
private Singleton() {}
9![]()
10
public static Singleton Instance
11
{
12
get
13
{
14
if (instance == null)
15
{
16
instance = new Singleton();
17
}
18
return instance;
19
}
20
}
21
}
22![]()
23![]()

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

1
//Static Initialization
2
public sealed class Singleton
3
{
4
private static readonly Singleton instance = new Singleton();
5
6
private Singleton(){}
7![]()
8
public static Singleton Instance
9
{
10
get
11
{
12
return instance;
13
}
14
}
15
}
16![]()
17![]()

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

1
//Multithreaded Singleton
2
using System;
3![]()
4
public sealed class Singleton
5
{
6
private static volatile Singleton instance;
7
private static object syncRoot = new Object();
8![]()
9
private Singleton() {}
10![]()
11
public static Singleton Instance
12
{
13
get
14
{
15
if (instance == null)
16
{
17
lock (syncRoot)
18
{
19
if (instance == null)
20
instance = new Singleton();
21
}
22
}
23![]()
24
return instance;
25
}
26
}
27
}
28![]()

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28
