I understand that anonymous types have no pre-defined type of its own. Type is assigned to it by the compiler at the compile type and details of type assigned at compile time can't be known at code level; these details are known to CLR itself. I've heard that these anonymous types at CLR are treated as if it's a reference type only. So my question is that whether at compile time a new Type like a class or a struct is created corresponding to read-only properties defined in the anonymous type?
I understand that anonymous types have no pre-defined type of its own.
Correct. There is no base type other than object common to anonymous types.
Type is assigned to it by the compiler at the compile type and details of type assigned at compile time can't be known at code level
That's correct.
these details are known to CLR itself.
I don't know what "details" you're talking about or what "known to CLR" means.
I've heard that these anonymous types at CLR are treated as if it's a reference type only.
You heard correctly.
So my question is that whether at compile time a new Type like a class or a struct is created corresponding to read-only properties defined in the anonymous type?
Yes. A new class is created.
Note that within an assembly if there are two anonymous types with the same property names, same property types, in the same order, then only one type is created. This is guaranteed by the language specification.
Exercise:
// Code in Assembly B:
public class B { protected class P {} }
// Code in Assembly D (references assembly B)
class D1 : B {
public static object M() { return new { X = new B.P() }; }
}
class D2 : B {
public static object M() { return new { X = new B.P() }; }
}
You are required to generate in assembly D a single class declaration that has a property X of type B.P such that D1.M().GetType()
is equal to D2.M().GetType()
. Describe how to do so.
Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
Source: https://msdn.microsoft.com/en-us/library/bb397696.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With