Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface<dynamic> not allowed in C# - workaround

I have a class that I am trying to design which uses dynamic as type parameter:

public class Idea : IEnumerable<dynamic>, IQueryable<dynamic>
{
}

Compiler: Cannot implement a dynamic interface

So I have this workaround which I'm not overly keen on:

public class Idea<T> : IEnumerable<T>, IQueryable<T>
{
}

public class Idea : Idea<dynamic>
{
}

Compiler: success!

I can't think of any other way to work around this issue, and I'm not really sure I want to expose Idea<T> to the user.

Questions:

  1. I feel like there are code smells here... can you confirm?
  2. Why does the CLR not allow implementation of dynamic interfaces?
  3. Are there any patterns I could use to achieve this without exposing Idea<T>?
like image 813
Matthew Layton Avatar asked Oct 21 '14 10:10

Matthew Layton


1 Answers

I had like to address your foremost question "Why does the CLR not allow implementation of dynamic interfaces?"

Simply because it doesn't make sense. Read this blog post of Chris Burrows that explains that thoroughly.

There are for example problems when overriding dynamic members, matching signatures, etc.

For example this line says a lot:

but it’s because when we look at method overrides and overloads, we treat object and dynamic as the same

Yeah, that is an issue. This sample was given in the article:

public class C
{
    public void M(object x) { }
    public void M(dynamic x) { }
}

That indeed doesn't make sense, and although the types seem to differ, in the CLR world they don't.

Although it seems to be possible, according to the CLI team, this needs a lot of more work to do. And they didn't find this useful to implement until now:

The metadata team reported that a reading of the CLI spec seemed to indicate that the tables for interface implementations and custom attributes might have permitted it, but anyway no one we know of has ever done this, and it would have been effort expended. We have priorities and a limited budget of time, and this didn’t make the cut.

To answer your other questions: Yes, you are right, the workaround feels bad, and it probably is, but it seems the only workable solution right now. Ask yourself if you really want and need this. If so, proceed with your current solution.

like image 97
Patrick Hofman Avatar answered Oct 05 '22 13:10

Patrick Hofman