C # A super practical type-Anonymous type
As the name implies, an anonymous type is a type without a name. When a new anonymous object definition is the same as the internal variable type of the existing type definition, the compiler will generate only one class definition instead of one. Anonymous objects can still contain anonymous objects.
In C #3.0, we can declare a temporary type in the program to store data, for example:
Class Program {static void Main (string [] args) {// declare an anonymous object with the Name and Age attributes var obj = new {Name = "Joey ", age = 25}; // here new {Name = "Joey", Age = 25} is an anonymous type, and obj is an object of this type, called the anonymous object Console. writeLine ("anonymous object obj: Name =" + obj. name + ", Age =" + obj. age );}}
In the above Code, an anonymous object obj is declared and the attribute value of the object is output.
If you move the mouse over var in front of obj in VS, vs will prompt that obj is an anonymous type 'a. This 'a is a type automatically identified by the compiler. When an anonymous object is compiled, the compiler still has to give it a type. In fact, the above anonymous type new {Name = "Joey", Age = 25} is inherited directly from the Object, which is equivalent
Public class 'a {
Public string Name {get; private set ;}
public int Age{get;private set;}
}
Such a custom type with read-only attributes.
In MSDN, the anonymous type is defined as follows:
1. The anonymous type provides a convenient method to encapsulate a set of read-only attributes into a single object without explicitly defining a type.
2. the type name is generated by the compiler and cannot be used at the source code level. The type of each attribute is inferred by the compiler.
3. You can use the new operator and object initial value to create an anonymous type.
The above three sentences are called "talking about ideas". Let people understand the anonymous type at a glance. However, I have to mention the relationship between the anonymous type and the declared keyword of var implicit type;
Many new users think this is an anonymous object when they see the var declaration. Objects of the anonymous type must be declared using var, but objects declared using var are not necessarily anonymous objects, for example, var n = 5; you can't say that n is an anonymous object. n is just an implicitly typed local variable. var s = new {S1 = "abc ", s2 = "def"}; s is an object of the anonymous type. That is to say, an anonymous object is a temporary type object declared in memory using var. Its type cannot be inferred based on the expression of the instance on the right like the implicit type. It is a real anonymous type, and var I = 5; this implicit type declaration, during compilation, I is actually int32 type, and implicit type is just a syntax.