Tips for writing beautiful C # code,

Source: Internet
Author: User

Tips for writing beautiful C # code,

I wrote my blog for the first time, but I don't know how to edit the code. Now, haha ....

I don't like reading blogs that copy and paste a bunch of code at will. So, let's use some simple examples to help you...

1. Automatic attributes.

1. Enter prop under vs and the Tab key will appear.

2. With Automatic attributes, we no longer need to define a private field for each public attribute of a class (actually not very useful ),

However, through reflection, we can still see the corresponding private field.

Example:

   

Ii. initialize the device.

If a list object is created and some elements need to be added.

1. The general practice is:

   

2. Use the initialization tool:

   

Iii. Double question mark and three-object operator.

If list is null, a new object is created.

1. The general practice is:

2. Use double question marks:

3. Use the Three-object OPERATOR:

4. Use the lamda expression.

When you need to calculate the number of Two Methods

1. The general practice is:

   

2. Use the lamda expression:

   

If 3 + 5 is required, you can directly call temp (3, 5). The returned result is 8.

 

Note: Func <int, int, int> is defined by the system with two parameters. The generic delegation of a returned value is defined as follows:

  

5. Use Linq.

If you want to filter out the elements whose ItemCode is "hello ",

1. General Practice:

  

2. Use Linq

  

Note: 1. Where is an extension method (defined by the this keyword). It is a function defined by the system and is defined as follows:

A. the first parameter source corresponds to the list above,

B. The second parameter predicate (the parameter type is Tsource, And the return type is bool ),

Corresponding lamda expression (o => o. ItemCode = "hello ")

  

 

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.