Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create .NET interface with static members?

In .NET 3.5, I'd like to create a singleton interface:

interface ISingleton <T>
{
  public static T Instance {get;}
}

Of course that doesn't work but is what I'd like. Any suggestions?

EDIT: I just want it to be known that all singeltons will have a static property named Instance of the class type. It is always there. An interface would be an explicit way to express this.

like image 685
4thSpace Avatar asked Jan 14 '09 21:01

4thSpace


People also ask

CAN interface have static members in C#?

C# 11 and . NET 7 include static virtual members in interfaces. This feature enables you to define interfaces that include overloaded operators or other static members.

Can interface members be static?

The implementation of static abstract interface members is provided by types that implement the interface. For . NET 6, you must enable preview features in your project to be able to mark an interface member as static abstract .

How do you make an interface static?

Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.

Can we create interface for static class?

Since you cannot instantiate a static class, static classes cannot implement interfaces.


2 Answers

An Interface can't, to my knowledge, be a Singleton since it doesn't actually exist. An Interface is a Contract that an implementation must follow. As such, the implementation can be a singleton, but the Interface can not.

like image 135
Matthew Brubaker Avatar answered Oct 26 '22 20:10

Matthew Brubaker


While I agree with other posters that singletons are very much over used, a possible solution to your question is to provide an abstract base class with a type parameter of the derived singleton:

public abstract class Singleton<T> where T : Singleton<T>
{
  private static T _instance;

  public static T Instance
  {
    get { return _instance; }
    protected set { _instance = value; }
  }
}

Any class that derives from Singleton will have a static Instance property of the correct type:

public class MySingleton : Singleton<MySingleton>
{
    static MySingleton()
    {
        Instance = new MySingleton();
    }

    private MySingleton() { } 
}

Before using something like this though you should really think about whether a singleton is required or if you are better off with a normal static class.

like image 24
Andrew Kennan Avatar answered Oct 26 '22 20:10

Andrew Kennan