9

If it possible

IList <dynamic> = new List <dynamic>;

or

class A <T> { }
class B: A <dynamic> { }

Why it is not possible to do

class U: IEnumerable <dynamic> {}

?

asked Jun 12, 2016 at 15:59

2 Answers 2

11

This is not allowed, as Chris Burrows (who helped create and implement dynamic) explains:

Well, for one thing, it doesn’t actually give you anything that you didn’t already have. The first thing and the second thing are already there if you implemented IEnumerable<object>. In that case, you still would have been able to define GetEnumerator the way we did, and you still can convert C to IEnumerable<dynamic> (again, because of the structural conversions). Think of it this way: if anyone ever looks directly at your type C, they are never going to "see" what interfaces you implement. They only "see" them when they cast, and at that point, your IEnumerable<dynamic> didn’t do them any good.

That’s a fine reason, but you might respond, why not let me do this anyway? Why impose this limitation that seems artificial? Good question. I encountered this for the first time when I was trying to get the compiler to emit these things, and I realized very quickly that there was no where for me to emit the [Dynamic] attribute that we use to mark dynamic types. 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.

answered Jun 12, 2016 at 16:03
5

The easiest way of thinking about it - dynamic is not a type.

dynamic is a compiler directive which turns off all compile-time checks, and implements them at runtime instead.

When you declare a variable dynamic:

dynamic t = 123;
t = t.Length; // crashes at runtime

actually you are declaring the variable as System.Object, then turning off all compile-time checks for expressions which involve that variable:

object t = 123;
unchecked_for_errors
{
 t = t.Length; 
}

You cannot use <dynamic> as if it were a type, because it really isn't one.
Use <object> instead.

answered Sep 22, 2016 at 9:38
1
  • That’s half an answer since you can see generic type has no problem consuming dynamic instead of object. They act as if they are defined with type. Commented Aug 1, 2018 at 14:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.