[. NET] C # efficient programming (i)-C # language habits

Source: Internet
Author: User
Tags instance method

C # language Habits directory
    • One, using attributes instead of accessible data members
    • Second, use running constant (readonly) instead of compile constant (const)
    • Third, it is recommended to use the IS or as operator instead of coercion type conversion
    • Iv. using the Conditional feature instead of #if conditional compilation
    • V. Provide the ToString () method for the type
    • Vi. Understanding the relationship between several equivalence judgments
    • Vii. Understanding the pitfalls of GetHashCode ()
    • It is recommended to use query syntax instead of looping
    • Ix. Avoid using conversion operators in the API
    • X. Using optional parameters to reduce the number of method overloads
    • Xi. Understanding the advantages of a short approach

One, using attributes instead of accessible data members

Second, use running constant (readonly) instead of compile constant (const)

1. C # has two types of constants: compile-time and run-times.

2. Try to use run-time constants instead of compile-time constants.

        /// <summary>        ///Compile constant Quantity/// </summary>         Public Const intNum = -; /// <summary>        ///Running constant Quantity/// </summary>         Public Static ReadOnly intYear = .;

3. Compile-time constants can only be used for numbers and strings, and the run-time is also a constant because it cannot be modified again after the constructor executes.

4.const is more efficient than ReadOnly, but has low flexibility.

Third, it is recommended to use the IS or as operator instead of coercion type conversion

1.as is more efficient and safer than a strong turn.

The 2.as operator cannot be used with value types because value types can never be null.

Iv. using the Conditional feature instead of #if conditional compilation

V. Provide the ToString () method for the type

1. A suitable ToString () version should be provided for the type, otherwise the consumer will be constructed from the row and used for display based on some properties of the class.

2.object the ToString () method provided by default returns the full name of the type with little meaning. such as: System.Drawing.Rect.

3. Override all types of ToString () to display summary information of the object in a straightforward and straightforward light.

Vi. Understanding the relationship between several equivalence judgments

1. The system provides 4 functions to determine whether two objects are "equal".

2. For the first two methods, we never redefine it, and we usually rewrite the Equals method.

3. Override the type of Equals to implement IEQUATABLE<T> if it is a struct, you need to implement istructuralequatable.

4. Referring to the same DataRow, it is considered equal, and if you want to compare the content instead of the reference address, you should rewrite the Equals () instance method.

5.Equals () instance method overriding principle: For all value types, you should override the Equals () method, and for reference types, override the method if it does not meet your needs. Overriding the method also requires overriding the GetHashCode () method.

6.operator = = (): Whenever you create a value type, you must redefine operator = = () because the system defaults to comparing two values by reflection to be equal and inefficient.

Vii. Understanding the pitfalls of GetHashCode ()

1. Avoid implementing GetHashCode () for most of the types we implement.

The overloaded version of 2.GetHashCode () must adhere to the following three principles:

(1) If two objects are equal (defined by operator = =), they must generate the same hash code.

(2) A,a.gethashcode () must remain unchanged for any one object.

(3) For all inputs, the hash function should generate a hash code in all integers according to the random distribution.

It is recommended to use query syntax instead of looping

Example:

            //1. Using Loops            varFoo =New int[ -];  for(inti =0; I < -; i++) {Foo[i]= i *i; }            //using query Syntax            varFoo2 = ( fromNinchEnumerable.range (0, -)Selectn * N). ToArray ();

1. Some method syntax does not have a corresponding query syntax, such as Take, Taskwhile, Skip, SkipWhile, Min, Max, and so on, you need to use method syntax.

Ix. Avoid using conversion operators in the API

X. Using optional parameters to reduce the number of method overloads

1. For the first release of an assembly, you can use optional parameters and named parameters as you wish. For subsequent releases, you must create overloads for additional parameters. This will ensure that the current program will still function properly. Also, in any subsequent release, avoid modifying the name of the parameter because the parameter name has become part of the public interface.

Xi. Understanding the advantages of a short approach

1. It is best to write the clearest code possible and give the optimization work to JIT completion. A common error optimization is that we put a lot of logic in a function that would reduce the overhead of additional method calls.

         Public stringTest (BOOLisTrue) {            varSB =NewStringBuilder (); if(isTrue) {sb. Appendline ("A"); Sb. Appendline ("B"); Sb. Appendline ("C"); }            Else{sb. Appendline ("E"); Sb. Appendline ("F"); Sb. Appendline ("G"); }            returnsb.        ToString (); }

When the Test method is called for the first time, the two branches of If-else are JIT-compiled, and in fact only one of them needs to be compiled, modified:

         Public string Test2 (bool  isTrue)        {            varnew  StringBuilder ();             if (isTrue)            {                return  Method1 ();            }             Else             {                return  Method2 ();            }        }

Now that the method is split, the two methods can be JIT-compiled as needed without having to compile all the first time.

2. You can have more than dozens of statements in the If-else branch, or a branch dedicated to handling errors that occur in the program, or a selective extraction of the code in each case in the switch statement.

3. A short method (typically with fewer local variables) makes it easier for the JIT to select which local variables to place in the register rather than on the stack.

4. Try to write short and concise methods.

"Bo Master" anti-bone Aberdeen

"Original" http://www.cnblogs.com/liqingwen/p/6754401.html

"Reference", "C # efficient Programming"

[. NET] C # efficient programming (i)-C # language habits

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.