C # anonymous type

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.