An anonymous type is a mechanism for automatically generating types based on initialization lists at initialization time, using object initializers to create objects of anonymous objects. Such as:
var oec=new {name= "oec2003", age=100}
Using the Var and new two keywords in the statement that created the object,
The var keyword is used to declare an object name of an anonymous type, unlike Var and object, which is a strong type, where it acts as a placeholder, and the compiler infers the actual type.
The new keyword is directly followed by a pair of curly braces, not a type name, because the name of the anonymous type is generated automatically by the compiler at compile time. The name and age of the curly braces are anonymous types of attributes, which can be seen to be directly assigned after name and time, without specifying the type, and by the compiler to infer their type, for example, after compiling name inferred to string and age to int. So we can see that the anonymous type gives us a lot of respect and flexibility, and it makes the code difficult to read.
The code above is compiled to produce a code similar to the following
class Anonymous1
{
private int _name = oec2003;
private int _age = 100;
public int a
{
get { return _name; }
set { _name = value; }
}
public int b
{ get { return _age; }
set { _age = value; }
}
}
In the same program, if the name, type, and order of the object initializers in the different anonymous types defined are the same, a different instance of the same anonymous type will be Immortal, as follows:
var oec1=new {Name="oec2003" ,Age=100}
var oec2=new {Name="oec2004" ,Age=200}
oec1=oec2
We can access members of anonymous types like this
var oec=new {Name="oec2003", Age=100}
string name=oec.Name;
int age=oec.Age