Tag Archives: designtime

Why can’t you declare a static method in an interface?

I’ve stated on Twitter a couple of times that I’d like to be able to declare static methods as part of my interface. My reasoning is: If an interface defines a contract in my code, why can’t a static method be part of that contract?

public interface ITryStatic {
    static void Foo();
    void Bar();
}

I found a great answer over in this forum.

In both Java and .NET, classes can only inherit from one class but a class can implement multiple interfaces. So consider the following code.

public interface ITryStatic {
    static void Foo();
}

public interface ITryAnotherStatic {
    static void Foo();
}


public class Whoops : ITryStatic, ITryAnotherStatic {
    public static void Foo() { printline("Foo"); }
}

ITryStatic staticWhoops;
staticWhoops.Foo(); //which one does it try? It doesn't matter since there's no code to run.
((Whoops)staticWhoops).Foo(); //Sure, but it defeats the purpose of using an interface.

Essentially the answer is: The compiler tries to run the code specified by the static method in a class. Since an interface doesn’t provide an implementation details, there is nothing to run. You could, if the compiler would let you, cast the interface to the concrete type that’s actually being represented. But that defeats the purpose of declaring an using an interface.

I do wonder if type inference could be used to route around this problem?