Just the other day I cam across a bug that actually took me a while to figure out.
Somehow it seemed that the wrong overload was executed when executing through an inherited interface. Take a look at this code.
class Program
{
static void Main(string[] args)
{
IBar bar = new Bar();
bar.Execute("TEST");
}
}
public interface IFoo
{
void Execute(string value);
}
public interface IBar : IFoo
{
void Execute(object value);
}
public class Foo : IFoo
{
public void Execute(string value)
{
Console.WriteLine("Foo.Execute - string");
}
}
public class Bar : IBar
{
public void Execute(string value)
{
Console.WriteLine("Bar.Execute - string");
}
public void Execute(object value)
{
Console.WriteLine("Bar.Execute - object");
}
}
The output from this program is "Bar-Execute - object" that for me seems a little strange since a more specific overload is available through the inherited IFoo interface. Can anyone explain this behavior?
Best regards
Bernhard Richter
I think in this blog you can find explanation: http://csharpindepth.com/Articles/General/Overloading.aspx
When the compiler goes looking for instance method overloads, it
considers the compile-time class of the "target" of the call, and
looks at methods declared there. If it can't find anything suitable,
it then looks at the parent class... then the grandparent class, etc.
This means that if there are two methods at different levels of the
hierarchy, the "deeper" one will be chosen first, even if it isn't a
"better function member" for the call.
Related
Please consider the following program:
using System;
public interface IFoo
{
void DoFoo();
}
public class Bar: IFoo
{
public void DoFoo() => Console.WriteLine("BAR!");
}
public class Baz: Bar, IFoo
{
void IFoo.DoFoo() => Console.WriteLine("baz!");
}
class Program
{
static void Main()
{
Baz baz = new Baz();
baz.DoFoo();
IFoo foo = baz;
foo.DoFoo();
Bar bar = baz;
bar.DoFoo();
IFoo foobar = bar;
foobar.DoFoo();
}
}
It gives the following output which I personally with my C++ background consider highly unexpected:
BAR!
baz!
BAR!
baz!
Having , IFoo in the declaration of Baz seems to be substantial, because otherwise void IFoo.DoFoo() doesn't compile.
Can someone please explain what is going on here (especially the last line)? And what should be done to prevent such behavior in real life? Should one avoid implementing from the same interface at all or there are some other rules to avoid problems?
UPD:
Looks like the principal problem here is not with "multiple inheritance" (which is not real multiple inheritance actually), but with the way interface methods can be implemented in C#. Namely, one can have two different implementations of the same method in the same class, one of which is explicit, another is implicit. E.g. this program:
using System;
public interface IFoo
{
void DoFoo();
}
public class Bar: IFoo
{
void IFoo.DoFoo() => Console.WriteLine("Foo!");
public void DoFoo() => Console.WriteLine("BAR!");
}
class Program
{
static void Main()
{
Bar baz = new Bar();
baz.DoFoo();
IFoo foo = baz;
foo.DoFoo();
}
}
prints
BAR!
Foo!
The trick with "multiple inheritance" just allows to introduce the explicit implementation from a derived class.
From my point of view this feature of C# is potentially dangerous, because if one implements a method of an interface, one usually expects the same method will be called no matter if it is invoked from the interface or from the class. And this is really the case if one implements everything only explicitly or only implicitly. But if both ways are used, this assumption is broken. So the moral seems to be:
Don't mix implicit and explicit implementation of the same method if you don't have in mind to employ this strange effect for some purpose.
Use explicit implementation in derived classes with caution.
This is a difference in the explicit implementation (void IFoo.DoFoo()) vs the implicit implementation (public void DoFoo()). The compiler will use the explicit implementation first. If you provide both an explicit and implicit implementation then the difference becomes clear:
https://dotnetfiddle.net/7l9gIs
using System;
public interface IFoo
{
void DoFoo();
}
public class Bar: IFoo
{
public void DoFoo(){ Console.WriteLine("BAR!"); }
}
public class Baz: Bar, IFoo
{
void IFoo.DoFoo(){ Console.WriteLine("baz explicit!"); }
public new void DoFoo(){ Console.WriteLine("baz implicit!"); }
}
public class Program
{
public static void Main()
{
Baz baz = new Baz();
baz.DoFoo();
IFoo foo = baz;
foo.DoFoo();
Bar bar = baz;
bar.DoFoo();
IFoo foobar = bar;
foobar.DoFoo();
}
}
Output
baz implicit!
baz explicit!
BAR!
baz explicit!
Implicit implementations tend to be more common and more convenient for usage. They are less verbose and any usage of the concrete type will have the implementations of the members exposed. Implicit implementations don't include the name of the interface being implemented before the member name, so the compiler infers this. The members will be exposed as public and will be accessible when the object is cast as the concrete type.
Visit this link for more details https://www.pluralsight.com/guides/distinguish-explicit-and-implicit-interface-implementation-csharp
The confusion is starting when you implement Baz from IFoo. Because Bar is already implements IFoo and Baz is the subclass of Bar. So, you dont need to do that.
In object oriented programming its not a best practice, in fact it is worst practice.
If you want to override DoFoo method, use the following code
public interface IFoo
{
void DoFoo();
}
public class Bar : IFoo
{
public virtual void DoFoo()
{
// do something
}
}
public class Baz : Bar
{
public override void DoFoo()
{
// override what you did in Bar class
}
}
In your code, when you try to baz.DoFoo, in fact you are calling bar.DoFoo.Because you didnt override it. Its the problem.
I'm realizing now that covariance is not available in abstract classes but is there anyway that I can utilize it here so that I can continue with this pattern.
Basically want the ability to create an instance of the first generic argument and pass the object which creates this object itself.
The below will fail at runtime because SpecialProcessor cannot be assigned to ProcessorBase with respect to generic types.
Appreciate any suggestions.
public class ProcessorUser<T> where T : ProcessorBase
{
public void ReceiveCommand()
{
Activator.CreateInstance(typeof (T), this);
}
}
public abstract class ProcessorBase
{
protected ProcessorBase(ProcessorUser<ProcessorBase> param)
{
}
}
public class SpecialProcessor : ProcessorBase
{
public SpecialProcessor(ProcessorUser<ProcessorBase> param)
: base(param)
{
}
}
Actually, from your less-than-complete code example, it's not clear at all a) what you are trying to do, and b) what "fails at runtime". You didn't show any code that calls the ReceiveCommand() method, so it's impossible to see in what way that code might fail.
That said, the usual way to gain access to variance in C# is through delegate or interface types. So you can declare a covariant interface to be implemented by ProcessorUser<T>, and then use that interface in the constructor declarations instead of the actual type. For example:
interface IProcessorUser<out T> where T : ProcessorBase
{
void ReceiveCommand();
}
class ProcessorUser<T> : IProcessorUser<T> where T : ProcessorBase
{
public void ReceiveCommand()
{
Activator.CreateInstance(typeof(T), this);
}
}
abstract class ProcessorBase
{
protected ProcessorBase(IProcessorUser<ProcessorBase> param)
{
}
}
class SpecialProcessor : ProcessorBase
{
private IProcessorUser<SpecialProcessor> _param;
public SpecialProcessor(IProcessorUser<SpecialProcessor> param)
: base(param)
{
_param = param;
}
public void ReceiveCommand() { _param.ReceiveCommand(); }
}
Note that I added the ReceiveCommand() method to the SpecialProcessor class just so I could see something execute at run-time. And that something does in fact work. But there's no way for me to know whether in your scenario, this is what you wanted to happen. You'd have to provide a good, minimal, complete code example that clearly shows what you are trying to do and what difficulty you are having doing it, if you want a clear, precise answer to that aspect of it.
(By the way, this really doesn't have anything to do with abstract classes. There's not even anything in your code example that is actually abstract, other than the class declaration itself, and the general principle applies to any class, not just abstract ones).
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.
Consider the following code:
abstract class Foo<T>
where T : Foo<T>, new()
{
void Test()
{
if(Bar != null)
Bar(this);
}
public event Bar<T> Bar;
}
delegate void Bar<T>(T foo)
where T : Foo<T>, new();
The line Bar(this) results in the following compiler Error:
Argument type Foo<T> is not assignable to parameter type T
T is constrained to Foo<T> as I want derived classes to basically tell the base class their type, so that the type can be used in the event callback in order to save the implementor from having to cast the callback argument to the derived type.
I can see the code doesn't quite work but I'm having a bit of a blockage as to how to do this correctly without ending up with a generic delegate that can be used for any old thing. I'm also not quite sure why the T constraint doesn't create a compiler error considering it seems to be recursive.
EDIT
I need to clarify this I think! Here's a new example which, I hope will be much clearer. Note below that the OnDuckReady event handler below generates a compiler error.
How do I get the event to pass in the correct type?
abstract class Animal<T>
where T : Animal<T>, new()
{
void Test()
{
if(AnimalReady != null)
AnimalReady(this);
}
public event AnimalHandler<T> AnimalReady;
}
delegate void AnimalHandler<T>(Animal<T> animal)
where T : Animal<T>, new();
class Duck : Animal<Duck>
{
public void FlyAway()
{
}
}
class Test
{
void Main()
{
Duck duck = new Duck();
duck.AnimalReady += OnDuckReady; // COMPILER ERROR
}
void OnDuckReady(Duck duck)
{
duck.FlyAway();
}
}
You can cast 'this' to T:
Bar((T)this);
This however will fail if you have the following:
public class MyFoo : Foo<MyFoo> { }
public class MyOtherFoo : Foo<MyFoo> { }
Because 'MyOtherFoo' is not an instance of 'MyFoo'. Take a look at this post by Eric Lippert, one of the designers of C#.
The code would be clearer if you didn't use "Bar" for two purposes. That having been said, I think what's needed is to use a generic with two parameters (e.g. T and U) such that T derives from U, and U derives from Foo. Alternatively, it's possible to do some nice things with interfaces. A useful pattern is to define:
interface ISelf<out T> {T Self<T> {get;}}
and then, for various interfaces that one might want to combine in an object:
interface IThis<out T> : IThis, ISelf<T> {}
interface IThat<out T> : IThat, ISelf<T> {}
interface ITheOtherThing<out T> : ITheOtherThing, ISelf<T> {}
If classes that implement IThis, IThat, and ITheOtherThing also implement ISelf<theirOwnTypes>, one can then have a routine whose parameter (e.g. "foo") has to implement both IThis and IThat accept the parameter as type IThis. Parameter "foo" will be of type IThis (which in turn implements IThis) while Foo.Self will be of type IThat. Note that if things are implemented this way, one may freely typecast variables to any desired combination of interfaces. For example, in the above example, if the object passed as "foo" was a type which implemented IThis, IThat, ITheOtherThing, and ISelf<itsOwnType> it could be typecast to ITheOtherThing>, or IThis, or any other desired combination and arrangement of those interfaces.
Really a pretty versatile trick.
Edit/Addendum
Here's a somewhat more complete example.
namespace ISelfTester
{
interface ISelf<out T> {T Self {get;} }
interface IThis { void doThis(); }
interface IThat { void doThat(); }
interface IOther { void doOther(); }
interface IThis<out T> : IThis, ISelf<T> {}
interface IThat<out T> : IThat, ISelf<T> {}
interface IOther<out T> : IOther, ISelf<T> {}
class ThisOrThat : IThis<ThisOrThat>, IThat<ThisOrThat>
{
public ThisOrThat Self { get { return this; } }
public void doThis() { Console.WriteLine("{0}.doThis", this.GetType()); }
public void doThat() { Console.WriteLine("{0}.doThat", this.GetType()); }
}
class ThisOrOther : IThis<ThisOrOther>, IOther<ThisOrOther>
{
public ThisOrOther Self { get { return this; } }
public void doThis() { Console.WriteLine("{0}.doThis", this.GetType()); }
public void doOther() { Console.WriteLine("{0}.doOther", this.GetType()); }
}
class ThatOrOther : IThat<ThatOrOther>, IOther<ThatOrOther>
{
public ThatOrOther Self { get { return this; } }
public void doThat() { Console.WriteLine("{0}.doThat", this.GetType()); }
public void doOther() { Console.WriteLine("{0}.doOther", this.GetType()); }
}
class ThisThatOrOther : IThis<ThisThatOrOther>,IThat<ThisThatOrOther>, IOther<ThisThatOrOther>
{
public ThisThatOrOther Self { get { return this; } }
public void doThis() { Console.WriteLine("{0}.doThis", this.GetType()); }
public void doThat() { Console.WriteLine("{0}.doThat", this.GetType()); }
public void doOther() { Console.WriteLine("{0}.doOther", this.GetType()); }
}
static class ISelfTest
{
static void TestThisOrThat(IThis<IThat> param)
{
param.doThis();
param.Self.doThat();
}
static void TestThisOrOther(IThis<IOther> param)
{
param.doThis();
param.Self.doOther();
}
static void TestThatOrOther(IThat<IOther> param)
{
param.doThat();
param.Self.doOther();
}
public static void test()
{
IThis<IThat> ThisOrThat1 = new ThisOrThat();
IThat<IThis> ThisOrThat2 = new ThisOrThat();
IThis<IOther> ThisOrOther1 = new ThisOrOther();
IOther<IThat> OtherOrThat1 = new ThatOrOther();
IThis<IThat<IOther>> ThisThatOrOther1 = new ThisThatOrOther();
IOther<IThat<IThis>> ThisThatOrOther2a = new ThisThatOrOther();
var ThisThatOrOther2b = (IOther<IThis<IThat>>)ThisThatOrOther1;
TestThisOrThat(ThisOrThat1);
TestThisOrThat((IThis<IThat>)ThisOrThat2);
TestThisOrThat((IThis<IThat>)ThisThatOrOther1);
TestThisOrOther(ThisOrOther1);
TestThisOrOther((IThis<IOther>)ThisThatOrOther1);
TestThatOrOther((IThat<IOther>)OtherOrThat1);
TestThatOrOther((IThat<IOther>)ThisThatOrOther1);
}
}
}
The thing to note is that some classes implement different combinations of IThis, IThat, and IOther, and some methods require different combinations. The four non-static classes given above are all unrelated, as are the interfaces IThis, IThat, and IOther. Nonetheless, it is possible for method parameters to require any combination of the interfaces provided that implementing classes follow the indicated pattern. Storage locations of a "combined" interface type may only be passed to parameters which specify the included interfaces in the same order. An instance of any type which properly implements the pattern, however, may be typecast to any "combined" interface type using any subset of its interfaces in any order (with or without duplicates). When used with instances of classes that properly implement the pattern, the typecasts will always succeed at run-time (they could fail with rogue implementations).
delegate void Bar<T>(Foo<T> foo) where T : Foo<T>, new();
It works great. I tested it.
here is the test code
public abstract class Foo<T> where T :Foo<T> {
public event Bar<T> Bar;
public void Test ()
{
if (Bar != null)
{
Bar (this);
}
}
}
public class FooWorld : Foo<FooWorld> {
}
public delegate void Bar<T>(Foo<T> foo) where T : Foo<T>;
class MainClass
{
public static void Main (string[] args)
{
FooWorld fw = new FooWorld ();
fw.Bar += delegate(Foo<FooWorld> foo) {
Console.WriteLine ("Bar response to {0}", foo);
};
fw.Test ();
}
}
I have various objects of different types.
For all of them, I want to call a static method of their class. All the classes share the same method.
How can I call this static method without explicitly calling the class?
You could accomplish this by putting a method in each object that calls the corresponding static method. However, the fact that you want to do this suggests that your design might be able to be improved. If you'd tell us what you're trying to accomplish, someone may be able to suggest a better approach.
If these classes all extend the same base class, then calling the method on the base class will work.
For example:
public class Base
{
public static DoSomething()
{
//something
}
}
public class A: Base
{
}
public class B: Base
{
}
The following method calls execute the same code:
A.DoSomething();
B.DoSomething();
Base.DoSomething();
You want to call every method on each of the individual classes? You have to call them explicitly, referencing each class individually.
Does the static method for every class have the same common code? Put it into a static class for use by all of the other classes, or create one or more extension methods.
Are you looking for something like you have something like List<object> where all of the objects are guaranteed to have a static method named, say MethodX() ?
If so you could reflect on them, look for the method name, and execute that.
Either that or inheritance like the others mention (which would be the correct way to go).
If you need to have a specific implementation for each type, I don't think a static method is the right approach... Instead, you shoud define an interface implemented by all your classes. You can then call the instance method defined by the interface on each object :
public interface IDoSomething
{
void DoSomething();
}
public class A: IDoSomething
{
public void DoSomething()
{
// implementation for A
}
}
public class B: IDoSomething
{
public void DoSomething()
{
// implementation for B
}
}
Of course, if you don't need a specific implementation for each type, then you can just call Base.DoSomething (as explained by David)
I'm not sure what exactly you're trying to do. But using my imagination I come up with this implementation.
internal class Program
{
private static void Main(string[] args)
{
var staticMethodClasses = new List<StaticMethodClassBase>
{new ClassA(), new ClassB()};
foreach (StaticMethodClassBase item in staticMethodClasses)
{
Type t = item.GetType();
MethodInfo staticMethod =
t.GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);
staticMethod.Invoke(null, null);
}
}
}
public abstract class StaticMethodClassBase
{
}
public class ClassA : StaticMethodClassBase
{
public static void DoSomething()
{
Console.WriteLine("Class A");
}
}
public class ClassB : StaticMethodClassBase
{
public static void DoSomething()
{
Console.WriteLine("Class B");
}
}