Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static method cannot implement interface method, why?

Tags:

c#

interface IXXX
{
    void Foo();
}

class XXX : IXXX
{
    public static void Foo()
    {
        Console.WriteLine("From XXX");
    }
}


class Program 
{
    static void Main(string[] args)
    {
        XXX.Foo();

    }
}

Compiler error: XXX.Foo() cannot implement an interface member because it is static.

Why can't a static method implement an interface method?

like image 933
xport Avatar asked Oct 18 '10 08:10

xport


2 Answers

See this thread from JoelOnSoftware describing the reasons behind this.

Basically the interface is the contract between the consumer and the provider, and a static method belongs to the class, and not each instance of the class as such.

An earlier question on SO also deal with the exact same question: Why Doesn't C# Allow Static Methods to Implement an Interface?

like image 138
Øyvind Bråthen Avatar answered Sep 20 '22 23:09

Øyvind Bråthen


An interface defines the behaviour that an object must respond to. As Foo is a static method, the object doesn't respond to it. In other words, you couldn't write...

XXX myXXX = new XXX();
myXXX.Foo();

In other words, myXXX doesn't fully satisfy the requirements of the interface.

like image 36
Richard Fawcett Avatar answered Sep 22 '22 23:09

Richard Fawcett