Straight Forward

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Singleton singleton = Singleton.Instance; 

sealed class Singleton
{
    public static Singleton Instance { get; } = new();

    private Singleton()
    {
    }
}

Null Checking

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Singleton singleton = Singleton.Instance; 

sealed class Singleton
{
    private static Singleton _instance = default!;
    public static Singleton Instance
    {
        get
        {
            if (_instance is null)
            {
                _instance = new Singleton();
            }

            return _instance;
        }
    }

    private Singleton()
    {
        Console.WriteLine("Instantiating singleton");
    }
}

Thread Safe

 1
 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
29
30
31
32
33
34

Singleton singleton = Singleton.Instance; 

sealed class Singleton
{
    private static Singleton _instance = default!;
    private static object _lock = new();

    public static Singleton Instance
    {
        get
        {
            if (_instance is null)
            {
                Console.WriteLine("Locking");

                lock (_lock)
                {
                    if (_instance is null)
                    {
                        _instance = new Singleton();
                    }
                }
            }

            return _instance;
        }
    }

    private Singleton()
    {
        Console.WriteLine("Instantiating singleton");
    }
}

using Dotnet Base Class Library (BCL)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Singleton singleton = Singleton.Instance;

sealed class Singleton
{
    private static readonly Lazy<Singleton> _lazyInstance = new(() => new());

    public static Singleton Instance => _lazyInstance.Value;

    private Singleton()
    {
        Console.WriteLine("Instantiating singleton");
    }
}

Jon Skeet way

 1
 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

Singleton singleton = Singleton.Instance;

sealed class Singleton
{
    public static string ClassName;

    public static Singleton Instance => Nested.Instance;

    private class Nested
    {
        internal static Singleton Instance { get; } = new();

        static Nested()
        {
        }
    }

    private Singleton()
    {
    }

    static Singleton()
    {
        ClassName = "asdf";
    }
}

Using Microsoft Dependency Injection Package

1
2
3
<ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
  </ItemGroup>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
using Microsoft.Extensions.DependencyInjection;

IServiceCollection services = new ServiceCollection();

services.AddSingleton<Singleton>();

var serviceProvider = services.BuildServiceProvider();

var instance = serviceProvider.GetRequiredService<Singleton>();

class Singleton()
{
}