3

I was recently browsing this question here on StackOverflow, and looking at the accepted answer I wonder what is the actual, concrete type of

var ordinals = new {
                       Test1 = SomeFunctionReturningInt32("Test1"),
                       Test2 = SomeFunctionReturningInt32("Test2")
                   };

What does this get MSILed to?

Community
  • 1
  • 1
User
  • 3,244
  • 8
  • 27
  • 48
  • 1
    `var type = ordinals.GetType();` It is compile time generated. The type should not concern you. – leppie Jul 13 '11 at 10:49

3 Answers3

8

It gets compiled into a generic internal type within your assembly. Something like:

internal sealed class SomeCompilerGeneratedNameHere<T1, T2>
{
    public SomeCompilerGeneratedNameHere(T1 test1, T2 test2)
    {
        ...
    }

    public T1 Test1 { get { ... } }
    public T2 Test2 { get { ... } }

    // Overrides for Equals, ToString, GetHashCode
}

Then in your case, it would use SomeCompilerGeneratedNameHere<int, int>. (The name itself is an "unspeakable" name, so you can't refer to it within your code explicitly, and there won't be any naming clashes with valid C# types.)

I can't remember offhand whether the constructor and properties are actually public or whether they're internal too - I know the type itself is internal.

All anonymous types with the same property names in the same order will use the same generic type, just potentially with different type parameters.

Note that this is implementation-specific - I don't believe the specification guarantees that generic types will be used; there could be one type per anonymous type used. The spec does guarantee that two anonymous type creation expressions will use the same type if they have the same property names and types in the same order.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That is interesting, I just opened my assembly in `ildasm`(`ildasm` shows all compile generated anonymous types in the bottom) and find out that for my case compiler generated single anonymous type (I am using same anonymous type to pass `Name` - `Value` parameters to a method multiple times). So `Single anonymous type` generated - specification works in that case. – angularrocks.com Feb 03 '14 at 01:09
2

The type is

<>f__AnonymousType0`2[System.Int32,System.Int32]

or something similar. You can easily find it out yourself like this:

Console.WriteLine(ordinals.GetType());
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

This will be a class with name like <>f_AnnonymousType03` - depends on various parameters. See also

VMAtm
  • 27,943
  • 17
  • 79
  • 125