C#. NET Code refinement optimization (The empty operator (?? ), as, string. IsNullOrEmpty (), String. Isnullorwhitespace (), String. Use of Equals (), System.IO.Path)

Source: Internet
Author: User
Tags type null

One, the empty operator (??). )
In a program, you often encounter a null operation on a string or an object, or a null value or a specified value. Usually we deal with this:

1,string name = value; if NULL ) {    string. Empty;}

2. Use ternary operator (? :) to optimize for the above:

string NULL string. Empty:value;

The above two ways of code is not concise,?? Operator for further optimization,?? The operator means that if the value to the left of the operator is null, the value to the right is taken.

string string. Empty;

Ii. using as conversion type
There are many ways to type conversion in C #, such as the coercion of type conversions, which are often used before conversion, so you may have written or seen code like the following

if  is Employee) {    var result = (Employee) obj;}

The above code does not report an exception, but two conversions are done throughout the process, which degrades performance. We can use the as operator for the conversion of the type, and also do not report the exception, if the type is incompatible, return NULL, but the conversion with as is the entire process is converted only once. The code is as follows:

var  as Employee; if NULL ){}

Third, in the automatic attribute, we can set the access level to the get or set accessor, make the property read-only property or write-only property

 Public class propertytest{    publicstringgetprivateset;}      Public Double Private Get Set ; }}

Four, String. IsNullOrEmpty (), String. Isnullorwhitespace ()
These two methods look at the name can also know IsNullOrEmpty is to judge the null reference and the empty string, and isnullorwhitespace is to determine whether the null reference and each character in the string is a space.
Requirements: Need to connect three names together, and want the middle name is not an empty string and no extra space, we will write the following code:

 Public stringFullName (stringName_1,stringName_2,stringname_3) {    if(stringName_2 = =NULL|| Mstring Name_2.trim (). Length = =0)    {        return string. Format ("{0} {1}", Name_1, name_3); }    return string. Format ("{0} {1} {2}", Name_1, name_2, name_3);} 

The above code uses trim to remove the space and then determine whether its length is 0, the code is very clear and concise, but will produce additional string objects that affect performance, then you should use the Isnullorwhitespace method in Net4.0 (the following code is very concise, And there's no need to worry about generating additional string objects that do not have a timely garbage collection effect on performance. )

 Public stringFullName (stringName_1,stringName_2,stringname_3) {    if(string. Isnullorwhitespace (name_2)) {return string. Format ("{0} {1}", Name_1, name_3); }    return string. Format ("{0} {1} {2}", Name_1, name_2, name_3);} 

V. String. Equals ()
String. The Equals method has a lot of overloads for us to use, but some of them are often overlooked by us.

 Public BOOL Equalstest (string  type) {    if (type. Equals ("1"))      {    }}

If the type is null throws a NullReferenceException exception, so in order not to throw an exception, before the judgment of the first to make a null judgment, to be written as follows

 Public BOOL Equalstest (string  type) {    if (type! =null && type. Equals ("1"))      {    }}

The solution above is equivalent to making two judgments each time, cumbersome and sometimes possibly forgotten, if you use String. equals can solve this problem.

 Public BOOL Equalstest (string  type) {    if (string"1"))  //type null does not throw an exception but returns false directly.     {    }}

It is sometimes necessary to distinguish between cases when the strings are equal, and many people are accustomed to converting them to size or smaller in comparison (it is recommended to convert to uppercase, because the compiler makes optimizations to improve performance), but when converted to uppercase or lowercase, the strings created will degrade performance. You should use Stringcomparison.invariantcultureignorecase at this time, the code is as follows

 Public BOOL Equalstest (string  type) {    if (string"1", strequityngcomparison.invariantcultureignorecase)))      {    }}

VI: System.IO.Path (we can use the static method of the path class when we encounter this need to manipulate the file path)
The System.IO.Path method in net has many static methods to handle files and paths. Many times we try to manually combine paths and filenames, resulting in a file path that is not available because we tend to overlook that there may be a trailing sign ' \ ' behind the path. Use the Path.Combine () method now to avoid this error

string FullPath = Path.Combine (WorkingDirectory, fileName);

Suppose you now have a full pathname with a file name, we need to take the path, file name, or extension of the file. Many of the static methods of the path class can meet our needs, as follows

string " d:\\downloads\\output\\pathtest.html "  string pathpart = Path.getpathroot (FullPath); // results: D:\ string Filepart = Path.getfilename (FullPath); // results: pathtest.html string Extpart = Path.getextension (FullPath); // result:. html string Dirpart = Path.getdirectoryname (FullPath); // Result: "D:\downloads\output"

C #,. NET Code refinement optimization (The empty operator (?? ), as, string. IsNullOrEmpty (), String. Isnullorwhitespace (), String. The usage of Equals (), System.IO.Path)

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.