How can I implement static methods on an interface?

You can't define static members on an interface in C#. An interface is a contract for instances.

I would recommend creating the interface as you are currently, but without the static keyword. Then create a class StaticIInterface that implements the interface and calls the static C++ methods. To do unit testing, create another class FakeIInterface, that also implements the interface, but does what you need to handle your unit tests.

Once you have these 2 classes defined, you can create the one you need for your environment, and pass it to MyClass's constructor.


You can define static methods in C# 8 but you must declare a default body for it.

public interface IMyInterface
{
      static string GetHello() =>  "Default Hello from interface" ;
      static void WriteWorld() => Console.WriteLine("Writing World from interface");
}

or if you don't want to have any default body simply throw an exception:

public interface IMyInterface
{
      static string GetHello() =>  throw new NotImplementedException() ;
      static void WriteWorld() => throw new NotImplementedException();
}

UPDATE:

Also, I should note in C# 11 you can have static abstract interfaces too, and abstract methods don't need default implementations

public interface IMyInterface
{
    static abstract string GetHello();
    static abstract void WriteWorld();
}

more info about static abstracts


Interfaces can't have static members and static methods cannot be used as implementation of interface methods.

What you can do is use an explicit interface implementation:

public interface IMyInterface
{
    void MyMethod();
}

public class MyClass : IMyInterface
{
    static void MyMethod()
    {
    }

    void IMyInterface.MyMethod()
    {
        MyClass.MyMethod();
    }
}

Alternatively, you could simply use non-static methods, even if they do not access any instance specific members.

Tags:

C#

.Net

Interface