C #/NET code streamlining optimization skills (1)

Source: Internet
Author: User
Document directory
  • 1 null operator (??)
  • 2. Use the as Conversion Type
  • 3. Automatic attributes
  • 4 stopwatch class
  • 5 static method using timespan
  • Summary

When writing code, we can use some tips to make the code more concise, easy to maintain, and efficient. The following describes several programming skills that are useful in C #/net.

1 null operator (??)

In a program, null is often used to judge a string or object. If it is null, a null value or a specified value is given. Usually we will handle it like this

string name = value;if (name == null){    name = string.Empty;}

You can use the ternary operator (? :) Is it optimized for the face?

string name = value == null ? string.Empty : value;

In this way, the code is much more concise, but this is not the most concise. Can we still use it ?? Operator for further optimization ,?? The operator indicates that if it is null, the value on the left of the operator is obtained; otherwise, the value on the right is obtained.

string name = value ?? string.Empty;

We can even write an extension method to filter out null and spaces so that the returned results can be better used ?? Operator

public static class StringUtility{    public static string TrimToNull(string source)    {        return string.IsNullOrWhiteSpace(source) ? null : source.Trim();    }}

The Code is as follows:

string name = string.TrimToNull(value) ?? "None Specified";
2. Use the as Conversion Type

There are many ways to perform type conversion in C #, such as forced type conversion. before conversion, is usually used for type determination, therefore, you may frequently write or have seen code similar to the following.

if (employee is SalariedEmployee){    var salEmp = (SalariedEmployee)employee;    pay = salEmp.WeeklySalary;    // ...}

The above Code does not report exceptions, but two conversion operations are performed throughout the process, which will reduce the performance. We can use the as operator to convert data types, and no exception is reported. If the data type is incompatible, null is returned. Instead, the entire process of conversion with as is only converted once. The Code is as follows:

var salEmployee = employee as SalariedEmployee;if (salEmployee != null){    pay = salEmployee.WeeklySalary;    // ...}
3. Automatic attributes

Automatic attribute is a new feature in C #3.0 and later versions, which makes the code more concise. We will write the following code before defining attributes.

public class Point{    private int _x, _y;    public int X    {        get { return _x; }        set { _x = value; }    }    public int Y    {        get { return _y; }        set { _y = value; }    }}

The automatic attribute code is much simpler.

public class Point{    public int X { get; set; }    public int Y { get; set; }}

In automatic attributes, we can set the access level for the get or set accessors to make the attributes become read-only or write-only.

public class Asymetrical{    public string ThisIsReadOnly { get; private set; }    public double ThisIsWriteOnly { private get; set; }}
4 stopwatch class

In program development, it is sometimes necessary to count how long a method or a stored procedure has been executed. For example, the time statistics function is required when testing the performance of some methods, naturally, the method is to record each time before and after the processing method, and then calculate the time difference, as shown below:

DateTime start = DateTime.Now;SomeCodeToTime();DateTime end = DateTime.Now;Console.WriteLine("Method took {0} ms", (end - start).TotalMilliseconds);

Although the time difference of datetime can be achieved, the time difference calculated by datetime is not very accurate. To be precise, we can use Win32 API to call pinvoke, but it is very troublesome and error-prone.

In this case, we need to use the stopwatch class, which must reference the namespace.System. Diagnostics

var timer = Stopwatch.StartNew();SomeCodeToTime();timer.Stop();Console.WriteLine("Method took {0} ms", timer.ElapsedMilliseconds);
5 static method using timespan

When we need to set a time interval in the program or wait for a long time before performing the next operation, we will usually write the following code:

Thread.Sleep(50);

The parameter 50 in the code above clearly refers to 50 milliseconds. This is the type defined during method definition and is not very flexible, in addition, we often use the int type to define the passed parameters. The code below the type

void PerformRemoteWork(int timeout) { ... }

The timeout in the code above refers to the second, millisecond, hour, or day, which needs to be defined by the developer. Such code is very unclear during the call, we can use timespan to solve this problem.

void PerformRemoteWork(TimeSpan timeout) { ... }

Called code

PerformRemoteWork(new TimeSpan(0, 0, 0, 0, 50));

This code is also a headache, because timespan has 5 constructors for overloading, as shown below:

TimeSpan();TimeSpan(long ticks);TimeSpan(int hours, int minutes, int seconds);TimeSpan(int days, int hours, int minutes, int seconds);TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds);

These loads are confusing during calls, and the code written is not very readable, if the above 50 is not familiar with the timespan constructor, it cannot be seen at a glance that it is 50 milliseconds. A better way is to use the static timespan method.

private static readonly TimeSpan _defaultTimeout=TimeSpan.FromSeconds(30);

The above Code call can also be written

PerformRemoteWork(TimeSpan.FromMilliseconds(50));

In this way, it is clear when writing a program or reading the code.

Summary

This article is based on a foreigner's blog. It is not a literal translation. For the original article, see the following link. These tips are not very complex, but they can be of great benefit in actual programming. I hope this article will help you.

Link: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/08/26/c.net-five-little-wonders-that-make-code-better-1-of.aspx

C #/NET code streamlining optimization skills (1)

C #/NET code streamlining optimization skills (2)

C #/NET code streamlining optimization skills (3)

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.