Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Java 1.6 @Override for interfaces in C#

This question gives the answer that Java's @Override has the C# equivalent of the override keyword on methods. However, since Java 1.6 the @Override annotation can be applied to interfaces also.

The practical use for this is that in Java you get compile errors when a class claims it implements an interface method when it no longer does (e.g. if the interface method is removed). Is there equivalent functionality in C#?

Some code examples:

Java:

public interface A {
  public void foo();
  // public void bar(); // Removed method.
}

public class B implements A {
  @Override public void foo();
  @Override public void bar(); // Compile error
}

C#:

public interface IA {
  void Foo();
  // void Bar(); // Removed method.
}

public class B : A {
  public override void Foo(); // Doesn't compile as not 'overriding' method
  public void Bar(); // Compiles, but no longer implements interface method
}
like image 860
Bringer128 Avatar asked Jan 20 '12 03:01

Bringer128


2 Answers

There is similar functionality: explicit interface implementation.

public interface IA { 
  void foo(); 
  // void bar(); // Removed method. 
} 

public class B : IA { 
  void IA.foo() {}
  void IA.bar() {} // does not compile
} 

The problem is that if you do this you cannot call the methods through the this pointer (from inside the class) or through an expression that evaluates to a B -- it is now necessary to cast to IA.

You can work around that by making a public method with the same signature and forwarding the call to the explicit implementation like so:

public class B : IA { 
  void IA.foo() { this.foo(); }
  public void foo() {}
} 

However this isn't quite ideal, and I 've never seen it done in practice.

like image 86
Jon Avatar answered Oct 29 '22 14:10

Jon


Not really, although VB.Net does.

You could implement the method explicitly and have that call the normal public version:

public void bar() { ... } 
void IA.bar() { bar(); }
like image 33
SLaks Avatar answered Oct 29 '22 15:10

SLaks