Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9074705
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T18:41:59+00:00 2026-06-16T18:41:59+00:00

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

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T18:42:00+00:00Added an answer on June 16, 2026 at 6:42 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I remember seen some code xaml where can get the first element (like an
First: sorry for my poor English writing. I remember that in VB6.0 days, we
I distinctly remember from the early days of .NET that calling ToString on a
First i selected images from photo library to ALAsset Library and after that i
I have a .net page with a multiview control. In the first view I
When manipulating controls on a .NET windows form which of the following is best
Remember the little div that shows up at the top of the page to
Please remember that I am not using any ORM tool. I have just written
I'm building a .net web app and using Forms authentication with cookies to remember
I'm already developing that project to my family, but now i'm needing to link

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.