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,
// http://blogs.msdn.com/ericwhite/pages/Tuples-and-Anonymous-Types.aspx

Resulting type full name and fully qualified name.

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

What compiler adds to the assembly?

image

 

Nice: DebuggerDisplayAttribute gets generated for the type

Nice: Overriden ToString() method.

Trace.WriteLine(anObject.ToString());

{ 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.IsNotNull(pis);
Assert.AreEqual(2, pis.Length);

foreach (PropertyInfo pi in pis)
    Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
        "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

Links:
Good entry point: http://blogs.msdn.com/ericwhite/pages/Tuples-and-Anonymous-Types.aspx
Want to cast to/from the anonymous type? http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1145096&SiteID=1
Recommended to language geeks :) http://tomasp.net/articles/csharp3-concepts.aspx

Post a Comment