Sunday, January 27, 2008

Exploration on Reflection for the anonymous types in C# 3.0

Although some of the information may be trivial, the purpose was just to look a bit under the hood.

Creating an anonymous Type.

in the XmlSink.Common.UnitTests.dll:

namespace XmlSink.Common.UnitTests
var anObject = new { Id = 25, Name = "Test Name" };

// Also possible to create with projection,

Resulting type full name and fully qualified name.

<>f__AnonymousType0`2[[System.Int32, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089]], XmlSink.Common.UnitTests, Version=, Culture=neutral, PublicKeyToken=null

What compiler adds to the assembly?



Nice: DebuggerDisplayAttribute gets generated for the type

Nice: Overriden ToString() method.


{ Id = 25, Name = Test Name }

As this is just another type in the assembly - Access as to the standard type.

PropertyInfo[] pis = aType.GetProperties();

Assert.AreEqual(2, pis.Length);

foreach (PropertyInfo pi in pis)
        "Property found {0} with value {1}",
        pi.Name, pi.GetValue(anObject, null)));

Produces the following expected output:

Property found Id with value 25
Property found Name with value Test Name

To be answered:
? How to safely find out if type is anonymous
? How and why at all to generate anonymous type dynamically

Good entry point:
Want to cast to/from the anonymous type?
Recommended to language geeks :)

Post a Comment