50 suggestions for improving C # programming (1-5)

Source: Internet
Author: User

Translated from Objective C #


1. properties)
Abstract attributes can be placed in the interface definition. For example:
Public interface INameValuePair
{
String Name {get ;}
T Value {get; set ;}
}
Attribute processing is recommended for access to all private fields. All data members in the class should be private.
Attribute is actually a method within FCL.
The attribute can also be virtual, and a separate access modifier can be provided for individual get or set accessors. For example:
Public virtual string Name
{
Get;
Protected set;
}
Attributes are called inline methods during JIT compilation, so the speed is almost the same as that of common data members.
Do not perform lengthy calculations or cross-application access (for example, querying a database) in attributes ).


2. Prefer readonly instead of const
C # has two types of constants: compile-time (declared by const) and run-time (declared by readonly ).
The compile-time constant can be declared in the method, but the runtime constant cannot.
The compile time can only be atomic (built-in integer, floating point, enumeration, string, etc.), and the run time can be any type.
The most important thing is that the Readonly type variable is interpreted at runtime. IL will generate a common reference to the corresponding object, and the const variable will generate the corresponding value by IL, this will cause inconvenience to the later maintenance. The following code:
Public class UsefulValues
{
Public static readonly int StartValue = 5;
Public const int EndValue = 10;
}
In another assembly, you reference these values:
For (int I = UsefulValues. StartValue; I Console. WriteLine ("value is {0}", I );
After an event, you have modified the original assembly. After the modification:
Public class UsefulValues
{
Public static readonly int StartValue = 105;
Public const int EndValue = 120;
}
In this case, you want to output
Value is 105
Value is 106
...
Value is 119
Actually, nothing is output, because the for loop is already the following code:
For (int I = UsefulValues. StartValue; I <10; I ++)
Console. WriteLine ("value is {0}", I );
The const variable is a little faster than the readonly variable, because IL directly generates constant strings or numbers for it, and readonly is more flexible, so we should prefer readonly.


3. Prefer is and as instead of Cast
Use as for type conversion because it is safer and more effective.
The as and is operators cannot perform any user-defined type conversion. They never construct new objects themselves. Cast converts an object to the requested type. If Cast converts a high-precision type to a low-precision type, information may be lost.
Note: The as operator cannot be used for value types. The value type can only be Cast. In this case, the packing/unpacking operation is generated. In this case, we recommend that you use the is operator to determine the value type first. For example:
Object o = Factory. GetValue ();
Int I = 0;
If (o is int)
I = (int) o;
The is operator should be used when the as operator cannot be used for conversion.
A good object-oriented design should avoid type conversion, but sometimes you have to perform type conversion, using the as and is operators can clearly express your purpose.


4. Use conditional features instead of # if
# If/# endif is too easy to abuse and the Code created is hard to understand and debug. C # added the condition feature to indicate whether a method should be called. It is clearer than # if/# endif.
# If/# endif mode:
Private void CheckStateBad ()
{
// The Old way:
# If DEBUG
Trace. WriteLine ("Entering CheckState for Person ");
// Grab the name of the calling routine:
String methodName = new StackTrace (). GetFrame (1). GetMethod (). Name;
Debug. Assert (lastName! = Null, methodName, "Last Name cannot be null ");
Debug. Assert (lastName. Length> 0, methodName, "Last Name cannot be blank ");
Debug. Assert (firstName! = Null, methodName, "First Name cannot be null ");
Debug. Assert (firstName. Length> 0, methodName, "First Name cannot be blank ");
Trace. WriteLine ("Exiting CheckState for Person ");
# Endif
}
If it is compiled and generated in the Release mode, this method will be an empty method. If you call this method frequently, some overhead is generated. Sometimes, due to the improper location of # if/# endif, some errors may occur during Release compilation, such:
Public void Func ()
{
String msg = null;
# If DEBUG
Msg = GetDiagnostics ();
# Endif
Console. WriteLine (msg );
}
If you compile in Release mode, an error occurs.
Conditional features:
[Conditional ("DEBUG")]
Private void CheckStateBad ()
{
...
}
This feature tells the compiler that this method is only valid when debugging environment variables are detected.
Compared with # if/# endif, the condition feature generates more effective IL code.


5. ToString () is always provided ()
System. Object. ToString () is one of the most common methods in the. NET environment. You should provide a reasonable ToString () version for all client classes. By default, System. Object. ToString () returns a fully qualified name of the type, for example, System. Drawing. Rect. By implementing the IFormattable. ToString method, you can output data in your own format. Generally, you should override the ToString () method in all your types and output a brief and reasonable information. In specific cases, when you need to output specific information, you should implement the corresponding methods of the IFormattable interface and ICustomFormatter interface.

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.