How does Anonymous Type in C# Work?

Recently I encountered a question about this topic in a test. Below is the question.

var person = new { FirstName = "Jon", LastName= "Doe" };

What class is generated to present person by the compiler when running the above code?

  • <>f__AnonymousType0’2[System.String,System.String]
  • AnonymousType[String,String]
  • <>f__AnonymousType0’2[string,string]
  • <>f__AnonymousType0’2[System.Char[],System.Char[]]
  • AnonymousType0’2[System.String,System.String]
  • At first glance, I can rule out choice 2 and 5, the internal notation should not be that simple, and then I exclude the choice 3, as I think full qualification of type name should include namespace. I was struggling between 1 and 4, I though Char[] would save more space as the length of the string was determined at compiling time, but that turned wrong in the end.

    Let’s walk through the investigation. First thing first, create a project of Windows Console, and my Program.cs reads like:

    using System; namespace AnonymousType { class Program { static void Main(string[] args) { var person = new { FirstName = "Jon", LastName= "Doe" }; ReflectOverAnonymousType(person); Console.ReadKey(); } static void ReflectOverAnonymousType(object obj) { Console.WriteLine("obj is an instance of: {0}", obj.GetType().Name); Console.WriteLine("Base class of {0} is {1}", obj.GetType().Name, obj.GetType().BaseType); Console.WriteLine("obj.ToString() == {0}", obj.ToString()); Console.WriteLine("obj.GetHashCode() == {0}", obj.GetHashCode()); Console.WriteLine(); } } }

    Here I am reusing the function ReflectOverAnonymousType from Andrew’s [C# 6.0 and The .NET 4.6 Framework].

    The output displays only the name of the generated class type:

    The rest is to figure out the type of the properties: FirstName and LastName. I thought Ildasm would give me some useful information, but as a matter of fact, it does not:

    Have no idea about ‘<FirstName>j_Tpar’.

     

    Finally, I found an easy way to work it out, which is to execute GetType() on person object in Immediate Window:

    So, the correct answer is choice 1.

     

     

    Advertisements Share this:
    Like this:Like Loading... Related