43

First, remember that a .NET String is both IConvertible and ICloneable.

Now, consider the following quite simple code:

//contravariance "in"
interface ICanEat<in T> where T : class
{
  void Eat(T food);
}

class HungryWolf : ICanEat<ICloneable>, ICanEat<IConvertible>
{
  public void Eat(IConvertible convertibleFood)
  {
    Console.WriteLine("This wolf ate your CONVERTIBLE object!");
  }

  public void Eat(ICloneable cloneableFood)
  {
    Console.WriteLine("This wolf ate your CLONEABLE object!");
  }
}

Then try the following (inside some method):

ICanEat<string> wolf = new HungryWolf();
wolf.Eat("sheep");

When one compiles this, one gets no compiler error or warning. When running it, it looks like the method called depends on the order of the interface list in my class declaration for HungryWolf. (Try swapping the two interfaces in the comma (,) separated list.)

The question is simple: Shouldn't this give a compile-time warning (or throw at run-time)?

I'm probably not the first one to come up with code like this. I used contravariance of the interface, but you can make an entirely analogous example with covarainace of the interface. And in fact Mr Lippert did just that a long time ago. In the comments in his blog, almost everyone agrees that it should be an error. Yet they allow this silently. Why?

---

Extended question:

Above we exploited that a String is both Iconvertible (interface) and ICloneable (interface). Neither of these two interfaces derives from the other.

Now here's an example with base classes that is, in a sense, a bit worse.

Remember that a StackOverflowException is both a SystemException (direct base class) and an Exception (base class of base class). Then (if ICanEat<> is like before):

class Wolf2 : ICanEat<Exception>, ICanEat<SystemException>  // also try reversing the interface order here
{
  public void Eat(SystemException systemExceptionFood)
  {
    Console.WriteLine("This wolf ate your SYSTEM EXCEPTION object!");
  }

  public void Eat(Exception exceptionFood)
  {
    Console.WriteLine("This wolf ate your EXCEPTION object!");
  }
}

Test it with:

static void Main()
{
  var w2 = new Wolf2();
  w2.Eat(new StackOverflowException());          // OK, one overload is more "specific" than the other

  ICanEat<StackOverflowException> w2Soe = w2;    // Contravariance
  w2Soe.Eat(new StackOverflowException());       // Depends on interface order in Wolf2
}

Still no warning, error or exception. Still depends on interface list order in class declaration. But the reason why I think it's worse is that this time someone might think that overload resolution would always pick SystemException because it's more specific than just Exception.


Status before the bounty was opened: Three answers from two users.

Status on the last day of the bounty: Still no new answers received. If no answers show up, I shall have to award the bounty to Moslem Ben Dhaou.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • 14
    Stack Overflow needs a new flagging option: `"Flag for Jon Skeet"` – Bobson Nov 26 '12 at 19:27
  • 1
    Writing code like that is just silly :) – leppie Nov 27 '12 at 16:28
  • I kind of can see the issue. You want the type parameter explicitly bound to concrete types. – leppie Nov 27 '12 at 16:32
  • P.S. upvote just for the wolf-eat-sheep analogy; I've just put a lamb hotpot in the oven! – batwad Nov 27 '12 at 16:56
  • 2
    @leppie: ever worked for a project where you were not forced to write silly code? – Stefan Steinegger Nov 27 '12 at 17:38
  • @StefanSteinegger: probably not ;p (professionally) – leppie Nov 27 '12 at 17:47
  • My suggestion: Use explicit implementation for at least one of the two methods in such a case. – Olivier Jacot-Descombes Dec 04 '12 at 19:27
  • @OlivierJacot-Descombes I don't think it matters if the interfaces are implemented "implicitly" (by ordinary public methods) or explicitly. There's no problem in "assigning" which method belongs to which interface. See also the comments of batwad's answer. The problem lies in the contravariance. – Jeppe Stig Nielsen Dec 04 '12 at 19:51
  • Explicitly implemented methods can only be called through the interface like `((IClonable)wolf).Eat(s);` or `((IConvertible)wolf).Eat(s);`. The call `wolf.Eat(s);` is not possible if both methods are implemented explicitly and wolf is not statically typed as one of these two interfaces. – Olivier Jacot-Descombes Dec 04 '12 at 20:03
  • 1
    @OlivierJacot-Descombes (Note: `wolf` is neither `ICloneable` nor `IConvertible`. It is `ICanEat<>` in two ways.) Please try for yourself. Take my code for `HungryWolf`. Change both public methods into explicit interface implementations. Run the same two lines containing `Eat("sheep")`. How will you know which one of your two explicit interface implementations get run? Please make a comment again when you have tried this. – Jeppe Stig Nielsen Dec 04 '12 at 20:34
  • Sorry I still have VS2008. My guess was that it wouldn't compile. Contravariance seems to relax the use of explicitly implemented interfaces. – Olivier Jacot-Descombes Dec 04 '12 at 21:07
  • @OlivierJacot-Descombes: Could you look at http://stackoverflow.com/questions/13805847/why-does-vb-net-reject-assignment-to-nested-covariant-interface-as-ambiguous/13809781#13809781 and try that in vs2008? I vaguely recall that the code worked in 2008, but I don't have 2008 handy anymore. – supercat Dec 12 '12 at 17:38
  • VS 2008 does not have the `in` and `out` variance modifiers. – Olivier Jacot-Descombes Dec 12 '12 at 22:25

4 Answers4

9

I believe the compiler does the better thing in VB.NET with the warning, but I still don't think that is going far enough. Unfortunately, the "right thing" probably either requires disallowing something that is potentially useful(implementing the same interface with two covariant or contravariant generic type parameters) or introducing something new to the language.

As it stands, there is no place the compiler could assign an error right now other than the HungryWolf class. That is the point at which a class is claiming to know how to do something that could potentially be ambiguous. It is stating

I know how to eat an ICloneable, or anything implementing or inheriting from it, in a certain way.

And, I also know how to eat an IConvertible, or anything implementing or inheriting from it, in a certain way.

However, it never states what it should do if it receives on its plate something that is both an ICloneable and an IConvertible. This doesn't cause the compiler any grief if it is given an instance of HungryWolf, since it can say with certainty "Hey, I don't know what to do here!". But it will give the compiler grief when it is given the ICanEat<string> instance. The compiler has no idea what the actual type of the object in the variable is, only that it definitely does implement ICanEat<string>.

Unfortunately, when a HungryWolf is stored in that variable, it ambiguously implements that exact same interface twice. So surely, we cannot throw an error trying to call ICanEat<string>.Eat(string), as that method exists and would be perfectly valid for many other objects which could be placed into the ICanEat<string> variable (batwad already mentioned this in one of his answers).

Further, although the compiler could complain that the assignment of a HungryWolf object to an ICanEat<string> variable is ambiguous, it cannot prevent it from happening in two steps. A HungryWolf can be assigned to an ICanEat<IConvertible> variable, which could be passed around into other methods and eventually assigned into an ICanEat<string> variable. Both of these are perfectly legal assignments and it would be impossible for the compiler to complain about either one.

Thus, option one is to disallow the HungryWolf class from implementing both ICanEat<IConvertible> and ICanEat<ICloneable> when ICanEat's generic type parameter is contravariant, since these two interfaces could unify. However, this removes the ability to code something useful with no alternative workaround.

Option two, unfortunately, would require a change to the compiler, both the IL and the CLR. It would allow the HungryWolf class to implement both interfaces, but it would also require the implementation of the interface ICanEat<IConvertible & ICloneable> interface, where the generic type parameter implements both interfaces. This likely is not the best syntax(what does the signature of this Eat(T) method look like, Eat(IConvertible & ICloneable food)?). Likely, a better solution would be to an auto-generated generic type upon the implementing class so that the class definition would be something like:

class HungryWolf:
    ICanEat<ICloneable>, 
    ICanEat<IConvertible>, 
    ICanEat<TGenerated_ICloneable_IConvertible>
        where TGenerated_ICloneable_IConvertible: IConvertible, ICloneable {
    // implementation
}

The IL would then have to changed, to be able to allow interface implementation types to be constructed just like generic classes for a callvirt instruction:

.class auto ansi nested private beforefieldinit HungryWolf 
    extends 
        [mscorlib]System.Object
    implements 
        class NamespaceOfApp.Program/ICanEat`1<class [mscorlib]System.ICloneable>,
        class NamespaceOfApp.Program/ICanEat`1<class [mscorlib]System.IConvertible>,
        class NamespaceOfApp.Program/ICanEat`1<class ([mscorlib]System.IConvertible, [mscorlib]System.ICloneable>)!TGenerated_ICloneable_IConvertible>

The CLR would then have to process callvirt instructions by constructing an interface implementation for HungryWolf with string as the generic type parameter for TGenerated_ICloneable_IConvertible, and checking to see if it matches better than the other interface implementations.

For covariance, all of this would be simpler, since the extra interfaces required to be implemented wouldn't have to be generic type parameters with constraints but simply the most derivative base type between the two other types, which is known at compile time.

If the same interface is implemented more than twice, then the number of extra interfaces required to be implemented grows exponentially, but this would be the cost of the flexibility and type-safety of implementing multiple contravariant(or covariant) on a single class.

I doubt this will make it into the framework, but it would be my preferred solution, especially since the new language complexity would always be self-contained to the class which wishes to do what is currently dangerous.


edit:
Thanks Jeppe for reminding me that covariance is no simpler than contravariance, due to the fact that common interfaces must also be taken into account. In the case of string and char[], the set of greatest commonalities would be {object, ICloneable, IEnumerable<char>} (IEnumerable is covered by IEnumerable<char>).

However, this would require a new syntax for the interface generic type parameter constraint, to indicate that the generic type parameter only needs to

  • inherit from the specified class or a class implementing at least one of the specified interfaces
  • implement at least one of the specified interfaces

Possibly something like:

interface ICanReturn<out T> where T: class {
}

class ReturnStringsOrCharArrays: 
    ICanReturn<string>, 
    ICanReturn<char[]>, 
    ICanReturn<TGenerated_String_ArrayOfChar>
        where TGenerated_String_ArrayOfChar: object|ICloneable|IEnumerable<char> {
}

The generic type parameter TGenerated_String_ArrayOfChar in this case(where one or more interfaces are common) always have to be treated as object, even though the common base class has already derived from object; because the common type may implement a common interface without inheriting from the common base class.

Community
  • 1
  • 1
jam40jeff
  • 2,576
  • 16
  • 14
  • Accepted and upvoted. Regarding things being simpler with covariance: Suppose you have a class implementing `ICanProduce` and `ICanProduce` where `ICanProduce` is "out" in the generic parameter. Clearly, the most derived common base **class** of `string` and `char[]` is well-defined (it is `System.Object`). But there are also interfaces. `ICloneable` is a common interface of both `string` and `char[]`. But so is `IEnumerable` and `IEnumerable`. So even if the "last" common base class is easy to determine, we still have a problem with interfaces, I think. – Jeppe Stig Nielsen Jan 06 '13 at 18:40
  • +1 for the great explanation. This definitely deserves a higher rating. – atlaste Feb 12 '13 at 14:12
  • I've revised this answer. Here is a question about the variance I tried to solve: [[Evaluate the minimum covariance type to fit both of types](http://stackoverflow.com/questions/14472103/evaluate-the-minimum-covariance-type-to-fit-both-of-types)]. – Ken Kin Feb 16 '13 at 23:53
  • 1
    Thanks, Ken, for the reformatting and cleaning a couple things up. I went back through and tried to further clean up a couple things. Also, I changed the one bolding (of "the right thing") back to quotes to better convey that I mean "subjectively the right thing" rather than emphasizing it to be taken literally. – jam40jeff Feb 18 '13 at 05:33
  • 1
    It's no more better than the revision is within your agreement. Cheers! – Ken Kin Feb 21 '13 at 11:43
6

A compiler error could not be generated in such case because the code is correct and it should run fine with all types that does not inherit from both internal types at the same time. The issue is the same if you inherit from a class and an interface at the same time. (i.e. use base object class in your code).

For some reason VB.Net compiler will throw a warning in such case similar to

Interface 'ICustom(Of Foo)' is ambiguous with another implemented interface 'ICustom(Of Boo)' due to the 'In' and 'Out' parameters in 'Interface ICustom(Of In T)'

I agree that the C# compiler should throw a similar warning as well. Check this Stack Overflow question. Mr Lippert confirmed that the runtime will pick one and that this kind of programming should be avoided.

Community
  • 1
  • 1
Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93
  • 1
    Cannot be is a strong statement. The explanation you give why such a warning "cannot be" generated is insufficient to prove your point. – Hari Nov 27 '12 at 16:02
  • My explanation is why a compiler error cannot be generated not a warning. I clearly state that the C# compiler should throw a warning similar to VB.Net compiler – Moslem Ben Dhaou Nov 27 '12 at 16:31
  • Interesting and relevant thread you link there! Still this doesn't answer my question. – Jeppe Stig Nielsen Nov 27 '12 at 19:07
  • 1
    You haven't addressed the issue. The problem is not with the Wolf class, but the use of contravariant interface. The compiler should have found that there were 2 matching methods that could be invoked - hence compiler error. Saying that it should run if type does not implement both interfaces is like saying a overloaded methods are okay if a argument doesn't match more than 1. Try calling new HungryWolf().Eat("sheep"). You get an ambiguous invocation error. How is this different ? – Robert Slaney Nov 27 '12 at 19:53
  • If the T you are using inherit only from one interface both the runtime and the compiler will know which method to use (only one can be used because the second wont match the signature) therefore the code is acceptable to the compiler. Although a warning should be thrown in this case the same as VB does. – Moslem Ben Dhaou Nov 27 '12 at 22:49
  • "Sheep" is a string and still inherit from both interfaces. So this does not match my explanation. If you create a type that inherit from ICloneable but not fron IConvertible then there will be no issue. – Moslem Ben Dhaou Nov 27 '12 at 22:52
4

Here's one attempt at justification for the lack of warning or error that I just came up with, and I haven't even been drinking!

Abstract your code further, what is the intention?

ICanEat<string> beast = SomeFactory.CreateRavenousBeast();
beast.Eat("sheep");

You are feeding something. How the beast actually eats it up to the beast. If it was given soup, it might decide to use a spoon. It might use a knife and fork to eat the sheep. It might rip it to shreds with its teeth. But the point is as a caller of this class we don't care how it eats, we just want it to be fed.

Ultimately it is up to the beast to decide how to eat what it is given. If the beast decides it can eat an ICloneable and an IConvertible then it's up to the beast to figure out how to handle both cases. Why should the gamekeeper care how the animals eat their meals?

If it did cause a compile-time error you make implementing a new interface being a breaking change. For example, if you ship HungryWolf as ICanEat<ICloneable> and then months later add ICanEat<IConvertible> you break every place where it was used with a type that implements both interfaces.

And it cuts both ways. If the generic argument only implements ICloneable it would work quite happily with the wolf. Tests pass, ship that, thank you very much Mr. Wolf. Next year you add IConvertible support to your type and BANG! Not that helpful an error, really.

batwad
  • 3,588
  • 1
  • 24
  • 38
  • 3
    ... but ... you add another interface and existing code which calls `Eat(string)` is calling - probably - another implementation. Why? Because you added the new interface before the existing. **Did anyone ever say that the order of interfaces matters??** Raising an error could make adding an interface a breaking change. But ignoring the ambiguity makes it a roulette. – Stefan Steinegger Nov 27 '12 at 17:34
  • Why does saying `(new HungryWolf()).Eat("sheep");` give a compile-time error, you think? Try stripping away generic interfaces. Adding an extra overload to the `HungryWolf` class is, in your terminology, a breaking change. – Jeppe Stig Nielsen Nov 27 '12 at 18:47
  • This is where there is a different between implicit and explicit interface methods, and why I think the implicit version is just evil and should be avoided. Lets also implement ICanEat. How any types are both IComparable and IConvertible. At least the explicit version ( void ICanEat.Eat(IComparable comparable ) { } ) will not cause a compile failure if you're using HungryWolf directly. – Robert Slaney Nov 27 '12 at 20:04
  • @RobertSlaney Surely changing my two public instance methods into two explicit interface implementations won't change anything, so I don't see the relevance? – Jeppe Stig Nielsen Nov 28 '12 at 09:20
  • This answer is probably not the reason. See my other answer: `ICanEat` is not ambiguous, `HungryWolf` is. – batwad Nov 28 '12 at 11:34
  • Making the 2 interface methods explicit means that the HungryWolf instance needs to be cast to the interface before executing Eat. This way adding another version of ICanEat will never break existing code – Robert Slaney Nov 28 '12 at 23:22
  • @RobertSlaney The interfaces you implement explicitly are `ICanEat` and `ICanEat`. You cast the `HungryWolf` instance to `ICanEat`. Now, before, when you only implemented `ICanEat`, you knew what implementation got called. After, when you added the additional implementation, you have undefined behavior. You don't know which of your two explicit interface impl.s get called. It feels like a "breaking" change to me. – Jeppe Stig Nielsen Nov 29 '12 at 07:19
  • @JeppeStigNielsen: The term "undefined behavior" means describes situations where nothing is guaranteed and anything can happen (crashes, corrupted hard drives, spontaneous peaceful coexistence between cats and dogs, etc.) The situation here is nowhere near as drastic. Whether the `ICanEat.Eat` will bind to `ICanEat.Eat`, or bind to `ICloneable.Eat`, or sometimes bind to one and sometimes the other, is unspecified, but any particular call to `ICanEat.Eat` will cause exactly one call to one of the aforementioned routines. – supercat Dec 12 '12 at 23:06
  • @JeppeStigNielsen: Incidentally, there are many situations where ambiguity exists and where being able to explicitly favor one binding would be helpful, but even having the compiler arbitrarily pick one binding over another would be more useful than refusing to do anything. For example, code which needs something with a `Count` method could accept either an `ICollection` or an `ICollection`. If one has one method which accepts `ICollection` and one with a different name which accepts `ICollection`, something that implements both interfaces could be passed to either method, and... – supercat Dec 12 '12 at 23:23
  • @JeppeStigNielsen: ...for most implementations of those types, the effect would be the same. If the functions are overloaded to use the same name, however, types which implement exactly one of the interfaces would be passed to the proper method, but types which implement both couldn't be passed to *either* method. That seems unfortunate, since binding to either method, or even arbitrarily binding sometimes to one and sometimes the other would work just fine. It's only the refusal to bind to anything which causes problems. – supercat Dec 12 '12 at 23:27
  • @supercat Right, maybe "implementation dependent" is a better term than "undefined behavior". The former is used by [CS1956](http://msdn.microsoft.com/en-us/library/bb882526.aspx). If a class implemented both `ICollection` and `ICollection`, by two different properties, and you passed that object to a method that only accepted one of the interfaces, and if the **wrong** property got called, then that would be a **violation** of the specification. The compiler/runtime is not free to choose another property, that would be a **bug**. – Jeppe Stig Nielsen Dec 13 '12 at 12:36
  • @supercat Of course, semantically, the two `Count` ought to be the same integer, and it would be a very confusing design to have a class implement the two `Count` differently. But the compiler knows nothing about this semantics. It **must** use the property belonging to the right interface. – Jeppe Stig Nielsen Dec 13 '12 at 12:39
  • @JeppeStigNielsen: I agree that if there is no ambiguity, the compiler has no choice. My point was that there are many cases where there is ambiguity, but where having the compiler or runtime arbitrarily choose one of the individually-valid alternatives via any means (order of specification, phase of the moon, etc.) would be more helpful than refusing to use any of them. Of course, being able to somehow prioritize members would be even better yet, but even having a attribute which simply says "If this and some other alternative seem equally good, assume either will work" would help. – supercat Dec 13 '12 at 16:37
2

Another explanation: there is no ambiguity, therefore there is no compiler warning.

Bear with me.

ICanEat<string> wolf = new HungryWolf();
wolf.Eat("sheep");

There is no error because ICanEat<T> only contains one method called Eat with those parameters. But say this instead and you do get an error:

HungryWolf wolf = new HungryWolf();
wolf.Eat("sheep");

HungryWolf is ambiguous, not ICanEat<T>. In expecting a compiler error you are asking the compiler to look at the value of the variable at the point at which Eat is called and work out if it is ambiguous, which it not necessarily something that can it can deduce. Consider a class UnambiguousCow which only implements ICanEat<string>.

ICanEat<string> beast;

if (somethingUnpredictable)
    beast = new HungryWolf();
else
    beast = new UnambiguousCow();

beast.Eat("dinner");

Where and how would you expect a compiler error to be raised?

batwad
  • 3,588
  • 1
  • 24
  • 38
  • Maybe I expect the compiler error to come when `new HungryWolf()` (an expression of type `HungryWolf`) is implicitly converted (by contravariance) to `ICanEat`. It's a good question, but I feel there should be some compiler message _somewhere_. Are you aware of what happens if you say `class Eater { public void Eat(T t) { } public void Eat(S s) { } }` and then derive from the constructed generic type like so: `class Problem : Eater, ICanEat { }`. When `T` and `S` are the same, the two methods of `Eater` **unify**, and in this case the compiler cares! – Jeppe Stig Nielsen Nov 28 '12 at 11:46
  • I guess the compiler is only looking to make sure that converting `HungryWolf` to `ICanEat` is a valid conversion, which it is. Is there ambiguity in that conversion? I'm not sure. When the compiler raises errors about ambiguity, from what I can remember, it is when binding to a method. The method `Eat` isn't ambiguous on `ICanEat` and the implementation of `HungryWolf` isn't ambiguous in the same way as your `Problem` class is, though warning CS1956 it generates sounds like the sort of thing `HungryWolf` should generate, somewhere. Great question! – batwad Dec 03 '12 at 10:17
  • You say the `Eat` method is not ambiguous. So which one of the two overloads must the compiler use? `ate your CONVERTIBLE` or `ate your CLONEABLE`? – Jeppe Stig Nielsen Dec 03 '12 at 10:22
  • It's not ambiguous because you've defined `beast` as `ICanEat` and there is only one method called `Eat` which takes a `string` parameter on that interface, and you are passing it `"dinner"`. No ambiguity there. – batwad Dec 03 '12 at 10:57