Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
Hi,

Can anyone please help me to know why interface in C# cannot have static methods.

What I have tried:

I have tried like this then I got compile time error saying "The modifier static is not a valid for this item".
C#
public interface InterfacesEx
{
    static string Test();
}
Can anyone help me to know why static is not valid in interfaces?
Posted
Updated 30-Oct-22 7:21am

hi,

Suppose you could specify in an interface that a type had to have a particular static method than how would you call it? Polymorphism works through instances - whereas static members explicitly don't use instances.
that's the reason interfaces don't have static methods.
 
Share this answer
 
Comments
Maciej Los 27-Apr-17 14:25pm    
Nice explanation. +5
Because an interface is a "contract" or an agreement between the consumer (caller) and the provider (callee). An interface describes what and how the calle will provide functionality. There is no need for static members provided by a third party. Static members cannot be overridden by a provider so they do not belong in an interface.

.NET Questions (CLOSED) - Why can't you have static methods in an Interface?[^]
 
Share this answer
 
Comments
Maciej Los 27-Apr-17 14:25pm    
5ed!
Another way of looking at it:

If an interface could have a static method:
interface IFoo
{
    static void Bar();
}

class Foo1 : IFoo
{
    public static void Bar() { ... }
}

class Foo2 : IFoo
{
    public static void Bar() { ... }
}
and you invoked it:
IFoo.Bar();
there would be no way to known which implementation you would end up calling. Would that call Foo1.Bar or Foo2.Bar?

You might decide you want it to call both implementations. Which might work, until you introduce return values, or ref / out parameters:
C#
interface IFoo
{
    static int Bar();
}

class Foo1 : IFoo
{
    public static int Bar() { return 42; }
}

class Foo2 : IFoo
{
    public static int Bar() { return 84; }
}

int x = IFoo.Bar(); // What is the value of x?

An interface is a contract for things you can do with an instance of a class. A static interface, or static members on an interface, doesn't really make any logical sense.



Edit: Since this has been dragged back up into the "active" list, it's probably worth saying that as of C#11, this information no longer applies. Interfaces can now have static virtual members:
Explore static virtual members in interfaces | Microsoft Learn[^]
 
Share this answer
 
v2
Comments
Maciej Los 27-Apr-17 14:27pm    
Very good explanation based on examples!
5ed!
CHill60 31-Oct-22 10:20am    
5'd for both the original and the update. Hey - sometimes spam can be a good thing!? :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900