C# interface static method call with generics

29,525

Solution 1

Try an extension method instead:

public interface IMyInterface
{
     string GetClassName();
}

public static class IMyInterfaceExtensions
{
    public static void PrintClassName<T>( this T input ) 
        where T : IMyInterface
    {
         Console.WriteLine(input.GetClassName());
    }
}

This allows you to add static extension/utility method, but you still need an instance of your IMyInterface implementation.

You can't have interfaces for static methods because it wouldn't make sense, they're utility methods without an instance and hence they don't really have a type.

Solution 2

You can not inherit static methods. Your code wouldn't compile in any way, because a interface can't have static methods because of this.

As quoted from littleguru:

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

Solution 3

I also tried to setup a static method on an interface a little while ago, not sure why now. I did bookmark this so maybe it helps:

Interface with a static method by using extension methods

Solution 4

If you're just after the type name, you can just do this:

public class Helper
{
    static void PrintClassName<T>()
    {
         Console.WriteLine(typeof(T).Name);
    }
}

Solution 5

Declaring a static property, event or method on an interface definition is not considered a legal definition. This is because interfaces are considered contracts and as such, represent something that will be implemented by every client instance of that interface.

A static declaration essentially states that the static member does not require a physical client implementation in order to execute the required functionality and this falls short of the general concept of interfaces: providing a proven contract.

Share:
29,525
Toto
Author by

Toto

C# developper

Updated on May 09, 2020

Comments

  • Toto
    Toto about 4 years

    Is there a simple way to implement this, and if possible without instanciating an object :

    interface I
    {
         static  string GetClassName();
    }
    
    public class Helper
    {
    
        static void PrintClassName<T>() where T : I
        {
             Console.WriteLine(T.GetClassName());
        }
    }