Royi Namir
Royi Namir

Reputation: 148514

Get the Class type for dynamic type?

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) ?

Upvotes: 4

Views: 1430

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

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.

Upvotes: 6

Related Questions