As the name implies, an anonymous type is a type without a name. When a new anonymous object definition is the same as the intrinsic variable type defined by the previously existing type, the compiler generates only one class definition, not one. Anonymous objects can still be included in an anonymous type object.
In c#3.0 allows us to declare a temporary type in the program to store the data, for example:
class program { static void Main (string [] args) {//declares an anonymous object with the name and age property var obj = new {Name = " Joey ", age = 25 }; //here the new {Name = "Joey", age = 25} is an anonymous type, and obj is an object of this type, called an anonymous object Console.WriteLine ( "anonymous object Obj:name=" + obj. Name +
In the code above, we declare an anonymous object, obj, and then output the object's property values.
If in VS you move the mouse over the Var in front of obj, vs will prompt: Obj is an anonymous type ' a. This ' a ' is a compiler that automatically acts as a type of identity, and 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 directly inherited from object, equivalent to
public class ' a{
public string name{get;private set;}
public int Age{get;private set;}
}
Such a custom type that has a read-only property.
The definition of anonymous types in MSDN is this:
1. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.
2. The type name is generated by the compiler and cannot be used at the source code level. The type of each property is inferred by the compiler.
3. You can create an anonymous type by using the new operator and the object's initial value.
The above three sentences are called "talking points". The anonymous type can be understood at a glance. But here I have to mention the relationship between anonymous type and var implicitly typed declarative keywords;
Many novices see the Var declaration as an anonymous object, the object of an anonymous type must be declared with Var, but objects declared with VAR are not necessarily anonymous objects, such as Var n=5; You can't say n is an anonymous object, n is just an implicitly typed local variable, and var s=new{s1= "abc", S2= "def"}; S is an object of type anonymous type. That is, an anonymous object is an object of a temporary type declared in memory with Var. Its type cannot infer a type as an implicit type based on the instance of the right, it is a real anonymous type, and Var i=5; This implicit type of declaration, when compiled, I is actually a int32 type, an implicit type is just a syntax.
One type of C # Super utility-Anonymous type