C # Programming specifications and conventions

Source: Internet
Author: User
Tags bool comments datetime exception handling variables readable requires throw exception
Everyone can write code! A few months of programming experience will allow you to write "runnable applications". Making it work is easy, but coding in the most efficient way requires more work!
Remember, most programmers are writing "runnable code" rather than "efficient code". We mentioned earlier in this guide course, do you want to be your company's "most respected professional"? Writing "efficient code" is an art, and you must learn and practice it.
Naming conventions and conventions
Note: Pascal case-the first letter of all words is capitalized, other letters are lowercase.
ElCamel case-Except for the first word, the first letter of all words is capitalized, and other letters are lowercase.


Class names use Pascal case

public class HelloWorld;
Method uses Pascal case

public class HelloWorld
{
    void SayHello (string name);
}
Variables and method parameters use Camel case

public class HelloWorld
{
    int totalCount = 0;
    void SayHello (string name)
    {
        string fullMessage = "Hello" + name;
        // ...
    }
}
Don't use Hungarian methods to name variables. Previously, most programmers liked it-prefixing data types with variable names and m_ as a member variable. E.g:
string m_sName;
int nAge;
However, this method is not recommended in the .NET coding specification. All variables are in camel case, rather than prefixed by data type and m_.
命名 Name variables with meaningful, descriptive words
-Don't use abbreviations. Replace nam, addr, sal with name, address, salary, etc.
-Don't use single letter variables like i, n, x, etc. Use index, temp, etc.
Exceptions to variables used for loop iteration:

for (int i = 0; i <count; i ++)
{
 ...
}
If the variable is only used for iterative counting and does not appear elsewhere in the loop, many people still prefer to use a single letter variable (i) instead of another name.
-Do not use underscores (_) in variable names.
-The namespace needs to be named according to the standard pattern
...


The file name must match the class name
For class HelloWorld, the corresponding file name should be helloworld.cs (or, helloworld.vb)


Indentation and spacing
Indent TAB without SPACES.
Comments need to be aligned with the code.
Braces ({}) must be aligned with the code outside the parentheses.
Use a blank line to separate the logical grouping of the code.

bool SayHello (string name)
{
    string fullMessage = "Hello" + name; DateTime currentTime = DateTime.Now;
    string message = fullMessage + ", the time is:" + currentTime.ToShortTimeString ();
    MessageBox.Show (message);
    if (...)
    {
        // Do something // ... return false;
    } return true;
}
This code looks better than the above:

 bool SayHello (string name)
 {
  String fullMessage = "Hello" + name;
  DateTime currentTime = DateTime.Now;
  
  String message = fullMessage + ", the time is:" + currentTime.ToShortTimeString ();
  
  MessageBox.Show (message);
  
  If (...)
  {
   // Do something
   // ...
   
   Return false;
  }
  
  Return true;
 }
In a class, each method needs a blank line, which can only be separated by one line.
# p #
The curly braces should be on a separate line, instead of if, for, etc. can be on the same line as the parentheses.
it is good:

if (...)
{
    // Do something
}
not good:

if (...) {// Do something}
One space before and after each operator and parentheses.
it is good:

 if (showResult == true)
{
     for (int i = 0; i <10; i ++)
    {//
    }
}
not good: 
 

if (showResult == true)
  {
   for (int i = 0; i <10; i ++)
   {
    //
   }
  }
Good programming habits
Follow these good habits to write good procedures

bool SayHello (string name)
{
    string fullMessage = "Hello" + name; DateTime currentTime = DateTime.Now;
    string message = fullMessage + ", the time is:" + currentTime.ToShortTimeString ();
    MessageBox.Show (message);
    if (...)
    {
        // Do something // ... return false;
    } return true;
}
Avoid using large files. If the code in a file exceeds 300 to 400 lines, you must consider separating the code into different classes.
Avoid writing methods that are too long. A typical method code is between 1 and 25 lines. If a method sends more than 25 lines of code, you should consider breaking it down into different methods.
The method name needs to be able to see what it does. Don't use misleading names. If the names are self-explanatory, no documentation is needed to explain the function of the method.
it is good:

void SavePhoneNumber (string phoneNumber)
{
    // Save the phone number.
}
not good:

// This method will save the phone number.
void SaveData (string phoneNumber)
{
    // Save the phone number.
}
A method completes only one task. Don't combine multiple tasks into one method, even if those tasks are very small.
it is good:

 // Save the address.
 SaveAddress (address);
 // Send an email to the supervisor to inform that the address is updated.
 SendEmail (address, email);
 void SaveAddress (string address)
 {
  // Save the address.
  // ...
 }
 void SendEmail (string address, string email)
 {
  // Send an email to inform the supervisor that the address is changed.
  // ...
 }
not good:  

// Save address and send an email to the supervisor to inform that the address is updated.
 SaveAddress (address, email);
 void SaveAddress (string address, string email)
 {
  // Job 1.
  // Save the address.
  // ...
  // Job 2.
  // Send an email to inform the supervisor that the address is changed.
  // ...
 }
Use C # or VB.NET-specific types instead of alias types defined in the System namespace.
it is good:

 int age;
 string name;
 object contactInfo;
not good:

 Int16 age;
 String name;
 Object contactInfo;
Don't use a fixed value in the program, use a constant instead.

Don't use string constants. Use resource files.
Avoid using many member variables. Declare local variables and pass them to methods. Don't share member variables between methods. If a member variable is shared between several methods, it is difficult to know which method changed its value at what time.
使用 Use enum if necessary. Don't use numbers or strings to indicate discrete values.
it is good:

enum MailType
void SendMail (string message, MailType mailType)
{
    switch (mailType)
    {
        case MailType.Html:
        // Do something
        break;
        case MailType.PlainText:
        // Do something
        break;
        case MailType.Attachment:
        // Do something
        break;
        default:
        // Do something
        break;
    }
}
not good:

void SendMail (string message, string mailType)
{
    switch (mailType)
    {
        case "Html":
        // Do something
        break;
        case "PlainText":
        // Do something
        break;
        case "Attachment":
        // Do something
        break;
        default:
        // Do something
         break;
    }
}
Don't declare member variables as public or protected. Both are declared private and use public / protected Properties.
Do not use specific paths and drive names in your code. Use relative paths and make them programmable.
# p #
Never imagine that your code is running on the "C:" drive. You won't know that some users run programs on the network or "Z:" disk.
作 Do some "self-tests" when the application starts and make sure the required files and attachments are in the specified location. Check the database connection if necessary. If there is any problem, it will give the user a friendly prompt.
  Such as
If the required configuration file is not found, the application needs to be able to create a copy using the default values.
If an error value is found in the configuration file, the application will throw an error and give a prompt message to tell the user the correct value.
The error message needs to help the user solve the problem. Never use error messages like "application error" or "found an error". Instead, a specific message such as "Failed to update the database. Please ensure that the login id and password are correct."
When an error message is displayed, in addition to saying what is wrong, the user should be prompted how to solve the problem. Do not use something like "Failed to update the database." Prompt the user what to do: "Failed to update the database. Make sure the login id and password are correct."
The message displayed to the user should be short and friendly. But record all possible information to help diagnose the problem.
Comment
Don't comment every line of code, every declared variable.
注释 Annotate where needed. Readable code requires few comments. If all the variables and methods are named meaningfully, the code will be readable and not much commented.
A few comments will make your code look elegant. But if the code is unclear and poorly readable, it is bad.
If complicated and difficult principles should be used for some reason, equip the program with well-documented and re-divided comments.
初始化 Initialize a numerical variable with a value other than 0, -1, etc., and give reasons for choosing this value.
In short, write clear, readable code so that you can understand it without any comments.
做 Spell check the comments to ensure the correct use of grammar and punctuation.
Exception handling
Don't "catch the exception but do nothing". If you hide an exception, you will never know if the exception happened.
时 When an exception occurs, give a friendly message to the user, but accurately record all possible details of the error, including the time of occurrence, and related methods, class names, etc.
Only catch specific exceptions, not general ones.
it is good:

void ReadFromFile (string fileName)
{
    try
    {
        // read from file.
    }
    catch (FileIOException ex)
    {
        // log error.
        // re-throw exception depending on your case.
        throw;
    }
}
not good:

void ReadFromFile (string fileName)
{
    try
    {
        // read from file.
    }
    catch (Exception ex)
    {
        // Catching general exception is bad ... we will never know whether it
        // was a file error or some other error.
        // Here you are hiding an exception.
        // In this case no one will ever know that an exception happened.
        return "";
    }
}
It is not necessary to catch general exceptions in all methods. No matter what, let the program crash. This will help you find most errors during the development cycle.
You can handle all general exceptions with application-level (thread-level) error handlers. When encountering a general error other than ", this error handler should catch the exception, prompt the user with a message, and log the error message before the application closes or the user chooses" Ignore and Continue ".
It is not necessary to use try-catch for every method. Use only when specific exceptions may occur. For example, when you write a file, handle the FileIOException.
Don't write too big try-catch modules. If needed, write a separate try-catch module for each task performed. This will help you figure out which piece of code is causing the exception and issue a specific error message to the user.
If your application requires it, you can write your own exception class. Custom exceptions should not be derived from the base class SystemException, but inherited from IApplicationException.
not good:

 // Save the address.
SaveAddress (address);
 // Send an email to the supervisor to inform that the address is updated.
SendEmail (address, email);
void SaveAddress (string address)
{
    // Save the address. // ...
}
void SendEmail (string address, string email)
{
    // Send an email to inform the supervisor that the address is changed. // ...
}
it is good: 

// Save address and send an email to the supervisor to inform that the address is updated.
SaveAddress (address, email);
void SaveAddress (string address, string email)
{
    // Job 1.
    // Save the address.
    // ...
    // Job 2.
    // Send an email to inform the supervisor that the address is changed.
    // ...
}
http://www.builder.com.cn/2008/0720/997354.shtml

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.