Read improving C # code 157 recommendations: Recommended 4~6

Source: Internet
Author: User

Directory:

    • Recommendation 4: TryParse is better than parse.
    • Recommendation 5: use int? To ensure that a value type can also be null
    • recommendation 6: distinguish between the use of ReadOnly and const

first, suggest 4:tryparse than parse good

TryParse: A conversion exception occurred and an internal exception was handled. Returns false and Result=0

 Public Static BOOL TryParse (stringoutint result);

Parse: A conversion exception occurs and an exception is thrown.

 Public Static decimal Parse (string s);

Summary: TryParse will digest anomalies, and parse will not. If an exception is generated, the TryParse efficiency is higher than the parse.

Ii. Recommendation 5: Use int? To ensure that a value type can also be null

Why? ~ The database can be null for a field of type int; A certain scenario under 0 is of practical significance, but in order to differentiate between 0 and null.

The nullable<t> value type (where t:struct) can have null capability. Simplified to:T? (nullable<int>=int?)

 Public struct where struct

Int? More than int a null value:Int?=int (can be converted successfully); Int=int Requires special handling of NULL values)

Int?=int

int NULL ; int Ten  = Normalnum;

Int=int?

HasValue property: Determines whether there is a value; Value property: Specific value

int NULL  intten; if (nullablenum.hasvalue)      = Nullablenum.value; Else        0;

The idea is that if Nullablenum is null,normalnum=0 and NOT NULL, then the value is directly assigned.

so we can use?? simplify the above operations :

int NULL ; int Ten ;             0;

Of course it is suggested that sometimes abbreviations cause code readability to be reduced.

Open the current project and find that there are many areas that need to be optimized: readability and code cleanliness can be optimized

if (B.enablepush) {   ifnull)        = b.pushratio1.value;    if NULL )        = b.pushratio2.value;}                      

After modification:

if (B.enablepush) {       if  (b.pushratio1.hasvalue)           = b.pushratio1.value;        if (b.pushratio2.hasvalue)            = B.pushratio2.value;}

Open the project, look, there is a question: what is the difference??????? (similar to this)

DateTime T1 = DateTime.Now;             BOOL false ; // This sentence compilation does not pass null : T1;

To change this:

Datetime? T1 = DateTime.Now;             BOOL false ;D Atetime null : T1;

or this:

DateTime T1 = DateTime.Now;             BOOL false ;D atetime? t = flag? (DateTime?) null : T1;

Iii. recommendation 6: Distinguish between the use of ReadOnly and const

Usage scenarios:

The use of const is for efficiency, but not flexible enough.

The use of ReadOnly efficiency is not the first factor to consider, but flexible enough.

Difference:

ReadOnly (read-only): Run constant, no limit to the type of decoration. *readonly is a run-time constant and cannot be modified after the first assignment to it. The decorated reference type is the same as the reference.

Const (constant): compile-time constant; can only be decorated: primitive type, enum type, or string type. *const is a compile-time constant, and after we compile it, the value is fixed and cannot be modified. So it is also the default static modifier.

1, ReadOnly

Below, the compilation does not pass. Once the ReadOnly is assigned, it cannot be modified. The hint is also clear: You cannot assign a value to a read-only field.

class   People    {        publicreadonly String name="sunn";          Public  People()        {        }    }
people New people " Yuan " ; Console.WriteLine (p.name);

But we can assign values when the class is instantiated:

class people{        publicreadonly String name="sunn";          Public people ()        {            "Yuan";        }}  

We may normally write this by:

 Public Static ReadOnly String name="sunn";

Static we know that it belongs to the identity of the class, the act of unification, the common behavior. Behavior of non-singleton instances. If you want to modify a value, you need to assign it in a static constructor.

class people    {        publicstaticreadonly String name="sunn";         Static  people ()        {            "Yuan";        }          Public people ()        {                  }    }   

Suggested use:static readonly combination notation.

2. Const

In fact, the constant of the class, plus the static error. Because the compiler automatically adds static.

class people    {        publicconst"sunn";               }   

Il code: Discovery compiler added static to us

   Public Static string string ('sunn')

I was thinking, since it is regarded as a constant of the class, then we, this is not the drop ~ ~ because it is a compile constant, after the completion of the compilation can not modify the value :

class people    {        publicconst'sunn';         Static people ()        {            "Yuan";        }    }   

Read improving C # code 157 recommendations: Recommended 4~6

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.