C # syntactic sugar Article 1: Automatic attributes & amp; implicit type,

Source: Internet
Author: User

C # syntactic sugar Article 1: Automatic attributes & implicit types,

Today, I would like to share with you two simple knowledge points of C # syntactic sugar.

Automatic attributes: In C #4.0 and later versions, when the attribute accessors do not need other logic, the automatically implemented attribute can make the attribute Declaration more concise. The client code can also create objects through these attributes. Get and set accessors. "id =" mt3 "> as shown in the following example, when declaring an attribute, the compiler creates a private anonymous support field, which can only be accessed through the get and set accessors of the attribute.

In the past C #4.0, the attribute of the traditional method was used to encapsulate fields. Here I will briefly compare the differences and associations between the two methods:

1234567891011121314151617181920212223 public class AutoProperty     {         // Traditionally, fields must be defined to encapsulate attributes.         private string name;         public string Name         {             get return name; }             set { value = name; }         }         // Automatic attributes         public string LoginName { getset; }     }

From the perspective of the number of words in the Code, the traditional method of writing is cumbersome, and a line of code can be automatically attribute. What are the differences between the two functions, here I used the decompilation tool to check it out (The Decompilation tool is used. net Reflector 8.3), the specific effect is as follows:

Although there is no writing segment in the Code, the compiler will automatically generate fields for us. Then, we can see at the get and set accessors of each attribute

12345678910 // Traditional Methodpublic void set_Name(string value){    value = this.name;} public string get_Name(){    return this.name;}

  

123456789101112 // Automatic attributes[CompilerGenerated]public void set_LoginName(string value){    this.<LoginName>k__BackingField = value;} [CompilerGenerated]public string get_LoginName(){    return this.<LoginName>k__BackingField;}

  Note:From the code above, we can see that the format of the accesser is basically the same, that is, the automatic attribute accesser is marked as generated by the compiler, and then the field is also generated by the compiler. Therefore, the traditional method and automatic attributes have the same effect for compilation, but these tedious operation compilers help us generate the code to reduce the code written by programmers and make the logic of the Code clear, very short.

1. get and set accessors are required for automatically implemented attributes. To make the class unchangeable, declare the set accessors as private. Set accessor, you cannot use an object initializer to initialize the property. "id =" mt5 "> however, when declaring a private set accesser, you cannot use the initial object value to initialize the property. You must use constructors or factory methods.

12345678 public string CustomerId { getprivate set; }public AutoProperty(string _CustomerId)         {             this.CustomerId = _CustomerId;         }

Implicit type:You can infer the "type" var rather than the explicit type by assigning a local variable. The var keyword instructs the compiler to deduce the variable type based on the expression on the right of the initialization statement. The inferred type can be a built-in type, anonymous type, user-defined type, or. the type defined in the NET Framework class library, which is defined by Microsoft MSDN. In fact, the simple understanding of implicit type is that programmers can declare variables without specifying the type, and the compiler specifies the type based on the value. 2. If you need to have complex business logic in the attributes, you must use the traditional attributes. No matter what it is, it has its advantages and disadvantages, as long as we make proper use of it.

In theory, let's talk about a lot of things. Let's directly post the code below:

12345678910111213141516171819 public static void Test()         {              // Define variables in the traditional way             string CustomerId = "Customer";             var NewCustomerId = "Implicit type";             var Age = 20;             var Array = new string[] {"111","222"};             object objectstring = "object";             Console.WriteLine("Traditional type :"+CustomerId+" "+"Implicit type"+NewCustomerId); }

From the code above, we can see that only the first variable is to display the definition variable. Some people will see that it is not enough to define the Object directly. What is the benefit of this, I was puzzled at the beginning. Later I checked it with The Decompilation tool. Here I will directly map it:

From the above figure, we can see that the implicit type is automatically inferred based on the value on the right after being passed through the compiler, but the object type is still of the object type after being passed through the compiler. Therefore, the binning operation will occur, however, the implicit type is not boxed or deboxed, so the implicit type is better than the object type in terms of performance.

Considerations for using implicit types:

1. Initialization is required during definition.

2. Once Initialization is complete, you cannot assign values of different types to the variable and the initial value.

3. var must be a local variable.

Related Article

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.