The anonymous type may be a bit unfamiliar to some developers.
For a type, it is usually named, such as a Type named by the class and struct keywords mentioned in the value type and reference type.
Anonymous type: as the name suggests, the class or struct keyword is not used for naming. It is declared using the new keyword and object Initial Value (it is a reference type derived directly from the object ).
The initial values of the object can be named or unnamed. It provides a convenient method for us to encapsulate a set of read-only attributes into a single object without explicitly defining a type, which makes the code more concise.
The most optimal type for an anonymous type is anonymous. Therefore, we need to use the type inference (VAR keyword) to assign this type to an object.
The VaR keyword is a new feature that begins with C #3.0, called type inference. The inference type can be a built-in type, anonymous type, user-defined type, type defined in the. NET class library, or any expression.
Directly, the code is more intuitive. In the code, the names of the attributes A and B are the anonymous type initialized by the attributes C (not named), and a is the string type and B is the int type, c we use explicit conversion to (decimal) type (Note: anonymous types cannot be forcibly converted to any type other than object)
Using system;
Using system. Collections. Generic;
Using system. text;
Namespace blog. Sample
{
Class Program
{
Static void main (string [] ARGs)
{
VaR OBJ = new {A = "this is only a test", B = 10, c = (decimal) 20 };
Console. writeline ("anonymous value: \ n a = {0}, \ n B = {1}, \ n C = {2}", obj. a, obj. b, obj. c );
Console. Read ();
}
}
}
The last note is that, although it is anonymous, the compiler still assigns a name to it.
As shown in the preceding example, the anonymous type is only applicable to the current method.
For method calls other than methods, it is more appropriate to use a common naming structure or class (class or struct.