0

How can i implement a method from a class that is extended to an Interface?

I have this Interface:

public Interface myInterface
{
      public static int myMethod();
}

And this class:

public class MyClass : myInterface
{
       // And I want here to implement the method form myInterface and i don't know how
}
user1074030
  • 93
  • 3
  • 10

3 Answers3

5

Interface won't compile - change it to interface. static can't be part of an interface.

After corrections the code would look like this for example:

public interface myInterface
{
      int myMethod();
}

public class MyClass : myInterface
{
       public int myMethod()
       {
           return 1;
       }
}

Regarding static and interface see a quote from http://channel9.msdn.com/forums/TechOff/250972-Static-Inheritance/?CommentID=274217 :

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?

Jason Down
  • 21,731
  • 12
  • 83
  • 117
Yahia
  • 69,653
  • 9
  • 115
  • 144
0

You declared your interface incorrectly. Interface in C# specified with interface keyword, in that exact casing. Also interfaces cannot contain static methods. For further details please refer to Interfaces (C# Programming Guide) MSDN article.

Eugene Cheverda
  • 8,760
  • 2
  • 33
  • 18
-1

Second edit: shame on me. I gave this answer before I had tested it, then realized I had never declared a static method in an interface before. It isn't supported, there's an SO article here that covers it

disregard the answer below...

Simply implement the method as would normally:

public Interface myInterface
{
   static int myMethod();
}

//impl
public class MyClass : myInterface
{
   public static int myMethod()
   {
      //implementation here
   }
}

Edit: I had stated this would make the method callable from an instance of the abstract or concrete class, then realized I had forgotten it was an abstract method...

Community
  • 1
  • 1
BrMcMullin
  • 1,261
  • 2
  • 12
  • 28