Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Types C#

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?

like image 567
Programmer Avatar asked Dec 20 '16 19:12

Programmer


2 Answers

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.

like image 71
Eric Lippert Avatar answered Sep 27 '22 23:09

Eric Lippert


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

like image 34
Xiaoy312 Avatar answered Sep 28 '22 01:09

Xiaoy312