4

I wrote some code :

    public static object func()
    {
        return new { a = 1, b = 2 };
    }

   Console.WriteLine((func() as dynamic).a); //returns '1'.

If I can do : func() as dynamic so dynamic should be some kind of reference type / class.

I looked for its Class type but couldn't find any (via reflector).

what is its type ? ( reference type) ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

6

You can get the type via GetType() as normal.

That is an anonymous type, which is (as an implementation detail) a form of generic type. The name of the type is deliberately unpronounceable in c#.

If you look in reflector, there is probably an internal generic type somewhere ending in ’2 (to indicate 2 generic type parameters), with two properties "a" and "b", of the first and second generic type arguments respectively. It is a class, so a reference-type.

As a note:

new { a = true, b = 123.45 }

Would actually use the same generic type but with different generic type parameters.

Also; using dynamic doesn't change the object - it only changes how it is accessed.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • as int is an Alias to Int32 , does dynamic is an Alias to xxx ? – Royi Namir Nov 24 '11 at 18:38
  • @Royi ah, but things can actually **be** an int/Int32 (maybe boxed). No object is ever actually *of type dynamic*. In the same way that no object *is of type IFoo* (an interface). A **variable** (or expression) is of type dynamic; that just tells the compiler how to work with it - it doesn't *change* the actual object. – Marc Gravell Nov 24 '11 at 18:43
  • what is a real life scenario for which I will use dynamic ( not expando , and not in the context of return type of function) ? I know all the objects which im working with so what is the scenario in rel life which a "new unknown type" will come to me and I will have to deal with ...? – Royi Namir Nov 25 '11 at 10:00
  • @Royi COM or talking to an object from a dynamic language (Iron* maybe) would be good examples. Also, there are some fun things you can do with pattern-based methods - see Simple.Data. In most routine code, an interface would be a preferable abstraction – Marc Gravell Nov 25 '11 at 13:33