31

Take the following code:

ICanQuack quack = new Duck();
var map = (object) "a map";
quack.Fly((dynamic)map);

using those types

public interface ICanFly
{
    void Fly<T>(T map);
}

public interface ICanQuack : ICanFly
{
    void Quack();
}

public class Duck : ICanQuack
{
    public void Fly<T>(T map)
    {
        Console.WriteLine("Flying using a {0} map ({1})", typeof (T).Name, map);
    }

    public void Quack()
    {
        Console.WriteLine("Quack Quack!");
    }
}

Compiled with C# 5 compiler against .NET 4.5.1 (the behaviour is probably the same using older compiler/framework version) this generates the following error: enter image description here

Now, I have a pretty good idea what is happening under the covers (I blogged about it here) but I can't come up with a satisfying answer why?

Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
  • 4
    I suspect the answer may be "bug" :) But I'll look in more detail later. – Jon Skeet Nov 27 '13 at 13:01
  • 1
    Interesting question! I guess `dynamic` cannot be used as type parameter for generics because it is not an actual type. – Carsten Nov 27 '13 at 13:05
  • 2
    @Aschratt This is a nested interface issue. Check out his blog. – gleng Nov 27 '13 at 13:05
  • 2
    Based on Kyles answer, your question may be a duplicate of http://stackoverflow.com/questions/3696047/why-calling-isetdynamic-contains-compiles-but-throws-an-exception-at-runtim – Carsten Nov 27 '13 at 14:24
  • I agree with gleng; `dynamic` doesn't appear to know of base interfaces according to that error message. Not sure if that's true for all cases tho (as I extreme-rarely use `dynamic`). – MasterMastic Dec 09 '13 at 13:03
  • @JonSkeet Just came across this exact issue with some code we are doing. Are you aware if this is a bug as the link in the question is an 404 page. Thank you. – dreza Aug 13 '14 at 23:36
  • @dreza: Which link? I can only see one link in the question, and that works fine for me... – Jon Skeet Aug 14 '14 at 05:44
  • @JonSkeet oh, ok. Thanks for responding. I actually meant to say the link in the answer - https://connect.microsoft.com/VisualStudio/feedback/details/597276/dynamic-runtime-fails-to-find-iset-t-contains-during-runtime. I guess maybe I don't have permissions. Cheers anyway. – dreza Aug 14 '14 at 06:57

1 Answers1

13

I am guessing this situation has already been reported to Microsoft.

Take a look here

Rohit
  • 10,056
  • 7
  • 50
  • 82