Home > Software design >  Error while creating Singleton using interface with static property in C# 8.0
Error while creating Singleton using interface with static property in C# 8.0

Time:05-05

A problem occurred while creating a singleton using an interface with static properties.

public interface ISingleton<T> where T : new()
{
    static T instnace { get; set; }
    static T Instance
    {
        get
        {
            instnace ??= new T();
            return instnace;
        }
    }
}

public class Manager : ISingleton<Manager>
{
}

// TODO : Error!
var manager = Manager.Instance;

The problem is that I can't find the Instance property defined in that interface
Why can't I find that property?

CodePudding user response:

This is a bad practice so I would not use an interface like that but here is how it can be used.

public interface ISingleton<T> where T : new()
{
    static T Instance { get; } = new T();
}

public class Manager : ISingleton<Manager>
{
}

// then later
var manager = ISingleton<Manager>.Instance;

Or another solution could be something like this:

// this is an implementation similar to EmptyArray<T> internal BCL type.

public static class Singleton<T> where T : new()
{
    public static readonly T Instance = new T();
}

// then you can access it this way
var manager = Singleton<Manager>.Instance;

// Note: in this case the T type does not have to implement any specific interface.

Anyway, I suggest considering using a DI framework instead of manually implementing the singleton pattern.

CodePudding user response:

You call statics on the interface , not on the implementing class

 var manager = ISingleton<Manager>.Instance;
  • Related