Equivalent of Java 1.6 #Override for interfaces in C# - 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
}

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.

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(); }

As stated, you cannot get that kind of control from an interface alone in C#. You could get it from an abstract class however. For the purpose of completeness, here is what you could do:
public interface IA
{
void Foo();
//void Bar(); - removed
}
public abstract class A : IA
{
virtual void Foo()
{ }
// Removed method
//virtual void Bar()
//{ }
}
public class B : A
{
public override void Foo()
{ }
//throws an error like the one you were receiving regarding no method to override.
public override void Bar()
{ }
}

The #Override for interface in Java means 'implements'. When in Java a class implements an interface method and that method's signature is changed or the method is removed from the interface later the java compiler starts complaining about it.
This way it prevents the method to become 'dead code', you either have to remove the #Override annotation (so the method becomes a normal method) or remove or change the method to match the interface again. This is a very nice feature to keep your code clean. I would like C# to have this feature too.
I use explicit implementing as much as I can.
By the way: Resharper shows it when a method implements an interface method.

Related

Is it possible to call the explicit interface implementation of the base class in c#?

I would like this program to compile, and then print the output below:
public interface IFoo
{
void Bar();
}
public class FooBase : IFoo
{
void IFoo.Bar()
{
Console.WriteLine("Hello from base class.");
}
}
public class Foo : FooBase, IFoo
{
void IFoo.Bar()
{
(base as IFoo).Bar(); // doesn't compile
Console.WriteLine("Foo added some behavior!");
}
}
public static class Program
{
public static void Main(string[] args)
{
var foo = new Foo() as IFoo;
foo.Bar();
}
}
Desired output:
Hello from base class.
Foo added some behavior!
Obviously, the code above doesn't compile, because it's an invalid way to use the base keyword. Is there a way to accomplish this, without changing the implementation in the base class to a non-explicit one?
You can simply have the explicit interface implementation in the base class call a protected method in the class for its implementation. This allows other derived classes to still call that protected method while still explicitly implementing the interface (and also not publicly exposing the interface's method through the type itself, which presumably is the actual goal).

Interface inheritance consistency

First look at this code:
class Program
{
static void Main(string[] args)
{
var x =(Base) new Derived();
((IMethod)x).DoWork();
Console.ReadKey();
}
}
interface IMethod
{
void DoWork();
}
abstract class Base : IMethod
{
void IMethod.DoWork()
{
Console.WriteLine("Base.DoWork");
}
}
class Derived : Base, IMethod
{
public void DoWork()
{
//here I where I want to call base.DoWork();
Console.WriteLine("Derived.DoWork");
}
}
Output:
Derived.DoWork
Desired:
Base.DoWork
Derived.DoWork
I'm dealing with an API that exposes an interface that when implemented, the DoWork method will be called at some part of the procession.
Now in the above example, the class Base is a part of the API, that internally (in the API) already explicitly implements that interface and does some important executions in the DoWork method.
I need to override the implementation of the IMethod in my derived class as well, so I get notified when needed, the problem is I can't 'override' the method and call the base method, neither can I cast base to IMethod.
Any solution?
Note: reflection won't work since it's a Silveright project, and private method invoking is prohibited.
Are you able to just compose the classes, rather than using inheritance? Then you can implement DoWork() however you like, and still call DoWork() on the Base object as well. Since Base is abstract, you'll need to derive a dummy type to get everything to work.
class Derived : IMethod
{
private class SneakyBase : Base
{
// abstract implementations here
}
private IMethod baseObject = new SneakyBase();
void DoWork()
{
baseObject.DoWork();
// Custom DoWork code here
}
}
It's obviously a bit of pain to do things this way, but the API designers made an odd choice with the explicit interface implementation, and you're now paying for it.
Are you looking for:
public class Derived : Base
{
public override void DoWork()
{
base.DoWork();
}
}
I've found DanBryant's comment to be the answer, although as he mentions is a bit risky since we can't assure the implementer will call the base method, but is a decent way tho.
I made a protected virtual method that is called from the private interface implementer, then, in the derived class, instead of worrying about the interface, I just care about overriding the base class and calling the base implementation from it, that works perfect, example:
abstract class Base : IMethod
{
void IMethod.DoWork()
{
DoWork();
}
protected virtual void DoWork()
{
Console.WriteLine("Base.DoWork");
}
}
class Derived : Base
{
protected override void DoWork()
{
base.DoWork();
//here I where I want to call base.DoWork();
Console.WriteLine("Derived.DoWork");
}
}

Sealing an interface after implementing it

I am working on a small project and I came across that problem.
The project output is a library containing an interface. I would like to implement that interface and seal the functions in it like this if possible:
public interface ITest
{
void SomeMethod();
}
class A : ITest
{
public sealed override SomeMethod()
{
}
}
The idea is to have the interface available to everyone and have some specialized class that implements it. The exception is that I want to make sure that if someone create a specialized class of type A, he/she won't be able to change the method's behavior.
The problem is you can't put the "override" keyword in there since the method isn't declared as "virtual" in the interface. And you can't declare it as "virtual" in the interface since it's not allowed. And you can't remove the "override" keyword since it's needed by "sealed".
Any workaround or brainstorming idea would be welcome, but if someone can come up with a solution that includes an interface, I'd be really happy to learn it!
Thanks!
EDIT: Forget this question! Like Ani said, I forgot that by default method in C# are sealed. Seems like it's always good to go back to the basics once in a while...
I may have completely misunderstood the question, but if your intention is to seal the method in A, you can just do:
class A : ITest
{
public void SomeMethod() { ... }
}
Unlike Java, methods in C# are sealed by default. Subclasses of A won't be able to override the method since it hasn't been marked virtual.
On the other hand, if your intention is to mark the method 'almost sealed' in the interface, so that it forces upon an implementing class to immediately seal it, that isn't possible. It isn't (and shouldn't be) the business of the interface to dictate such details of implementation - an interface is meant to represent a specification.
Use an abstract base class with internal visibility. This base class is not visible outside of the library but allows you to seal the method and the class still implements the interface.
public interface ITest
{
void SomeMethod();
}
internal abstract class SuperA : ITest
{
public abstract void SomeMethod();
}
class A : SuperA
{
public sealed override void SomeMethod()
{
}
}
Your understanding of sealed keyword is incorrect. As a method modifier, sealed is used to prevent a virtual method(defined in the base class) to be override in the next generation of derived classes. For example:
class Base
{
public virtual void M() { }
}
class Derived : Base
{
public sealed override void M() { }
}
class A : Derived
{
public override void M() { } //compile error, M is sealed in Derived
}
Developers can always use new modifier to define a method with the same name in the derived class, that hides the one defined in the base class.
if someone create a specialized class
of type A, he/she won't be able to
change the method's behavior.
If "specialized class" means a class derived from A, the answer is: he can always hide the method in A, but he can't change the method's behavior.
Why not use an abstract class like below.
Haven't tested it but this should work?
public abstract class Test
{
public virtual void SomeMethod() {}
//OR
public abstract void SomeMethod();//MSDN says:
//an abstract method is implicitly virtual
}
class A : Test
{
public sealed override SomeMethod()
{
}
}
Methods in C# are sealed by default.. Here is a sample
class Program
{
static void Main(string[] args)
{
A obj = new A();
obj.SomeMethod();
b ss = new b();
ss.SomeMethod();
Console.ReadLine();
}
}
public interface ITest { void SomeMethod(); }
class A : ITest { public void SomeMethod() {
Console.WriteLine("SomeMethod Called from Class A object");
} }
class b : A
{
//public override void SomeMethod()
//{
// Console.WriteLine("Called from Class B Object");
//}
}

Get class type?

Given
public class A
{
public static void Foo()
{
// get typeof(B)
}
}
public class B : A
{
}
Is it possible for B.Foo() to get typeof(B) in .NET 4? Note that Foo is static.
There is no difference between A.Foo() and B.Foo(). The compiler emits a call to A.Foo() in both cases. So, no, there is no way to detect if Foo was called as A.Foo() or B.Foo().
Unfortunately this isn't possible, as dtb explains.
One alternative is to make A generic like so:
public class A<T>
{
public static void Foo()
{
// use typeof(T)
}
}
public class B : A<B>
{
}
Another possibility is to make the A.Foo method generic and then provide stub methods in the derived types that then call the "base" iplementation.
I'm not keen on this pattern. It's probably only worthwhile if you absolutely need to keep the B.Foo calling convention, you can't make A itself generic, and you have lots of shared logic inside A.Foo that you don't want to repeat in your derived types.
public class A
{
protected static void Foo<T>()
{
// use typeof(T)
}
}
public class B : A
{
public static void Foo()
{
A.Foo<B>();
}
}

Why am I getting an error in C# when mixing explicit implementation and polymorphism?

I am getting this error:
type Bar does not implement interface IFoo
From this code:
public interface IFoo
{
void DoA();
void DoB();
}
public class Foo:IFoo
{
void IFoo.DoA()
{
}
void IFoo.DoB()
{
}
}
public class Bar:Foo
{
void IFoo.DoA()
{
base.doA();
}
void IFoo.DoB()
{
base.doB();
}
}
I am using C# 2.0.
What am I doing wrong?
public class Bar : Foo, IFoo
{
// Your code
}
I have run into this as well. what is 'worse', depending on how you look at it is you can't define the interface implementations to be virtual to be overridden in descendent classes. I have gotten into the habit of doing this:
public class Foo:IFoo
{
void IFoo.DoA()
{
DoACore();
}
void IFoo.DoB()
{
DoBCore();
}
protected virtual void DoACore()
{
}
protected virtual void DoBCore()
{
}
}
public class Bar:Foo
{ protected override void DoACore()
{
base.DoACore();
}
protected override void DoBCore()
{
base.DoBCore();
}
}
See n8wrl's answer as to how you should be doing this. See below for the reason why.
You can't explicity implement interface members (void IFoo.DoA()) when implicitly implementing the interface. In other words, because Bar only implements IFoo by virtue of extending Foo, you cannot use explicit implementation.
This will work:
public class Bar : Foo
{
public void DoA()
{
...
}
public void DoB()
{
...
}
Or this:
public class Bar : Foo, IFoo
{
void IFoo.DoA()
{
...
}
void IFoo.DoB()
{
...
}
A bigger problem that you'll probably face is that since Foo is not abstract, it must implement DoA and DoB. If you also implement these methods in bar, you will not be doing it polymorphically. You'll be hiding the Foo implementations if the code has a handle to the Bar type.
I would suspect the confusion arises over how interfaces were implemented in C++, as abstract classes and multiple inheritance.
In .NET, and interface is simply a contract that says you will implement those methods.
You're code won't compile for the same reason this code wont compile(it would with C++):
public interface IFoo
{
void DoSomething();
}
public abstract class Foo : IFoo
{
}
Foo is declaring that Foo implements IFoo, it doesn't say anything else about anyone.
If you wanted to force derived classes to implement it you would do:
public interface IFoo
{
void DoSomething();
}
public abstract class Foo : IFoo
{
public abstract void DoSomething();
}
Or if you really wanted the interface methods hidden by explicit implementation, then something like n8wrl posted above.
At first, this is not clear what is the task? If the goals was to fix a problem asap, than 'Bar : Foo, IFoo' is the shortest solution.
If you are just trying to learn 'implicit/explicit' interfaces difference, than check this post.
Also notice, that 'n8wrl' solution is arguable. It is ok only if Foo indeed required to implement IFoo explicitly. If no, than there is a simpler way:
public interface IFoo
{
void DoA();
}
public class Foo : IFoo
{
public virtual void DoA() {}
}
public class Bar : Foo
{
public override void DoA() {}
}
Hope this helps.

Categories

Resources