C # Coding & Naming conventions

Source: Internet
Author: User
Tags finally block uppercase letter

Reference Document

Https://msdn.microsoft.com/en-us/library/ff926074.aspx

https://msdn.microsoft.com/en-us/library/ms229045 (v=vs.110). aspx

Coding conventions

Layout conventions

Use the default Code Editor settings (Smart indenting, Four-character indents, tabs saved as spaces).

Write only one statement per line.

Write only one declaration per line.

IF continuation lines is not indented automatically, indent them one tab stop (four spaces).

ADD at least one blank line between method definitions and property definitions.

Use parentheses to make clauses in a expression apparent, as shown in the following code.

if ((Val1 > Val2) && (Val1 > val3)) {//Take appropriate action.}

Comment conventions

Place the comment in a separate line, not at the end of a line of code.

Begin comment text with a uppercase letter.

End comment text with a period.

Insert one space between the comment delimiter (//) and the comment text, as shown in the following example

The following declaration creates a query. It does not run//the query.

Do not create formatted blocks of asterisks around comments.

Language guidelines

String Data Type

Use the + operator to concatenate short strings, as shown in the following code.

String displayName = Namelist[n]. LastName + "," + namelist[n]. FirstName;

To append strings in loops, especially if you were working with large amounts of text, use a StringBuilder object.

var phrase = "Lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala"; var manyphrases = new  StringBuilder (); for (var i = 0; i < 10000; i++) {    manyphrases.append (phrase);}  

Implicitly Typed Local Variables

Use implicit typing for local variables when the type of the variable are obvious from the right side of the assignment, or When the precise type was not important.

var var1 = "This is clearly a string." var var2 = var3,var = convert.toint32 (Console.ReadLine ()); 

Do not use Var if the type is not apparent from the right side of the assignment.

When the type of a variable are not clear from the context, use an explicit type.int VAR4 = Exampleclass.resultsofar ();

Do not rely the variable name to specify the type of the variable. It might not being correct.

Naming the following variable inputint is misleading. It is a string.var inputint = console.readline (); Console.WriteLine (inputint);

Avoid the use of Var in place of dynamic.

Use implicit typing to determine the type of the loop variable in for and foreach loops.

The following example uses implicit typing in a for statement.

var syllable = "Ha"; var laugh = ""; for (var i = 0; I < 10; i++) {    laugh + = syllable;    Console.WriteLine (laugh);}   

The following example uses implicit typing in a foreach statement.

foreach (Var ch in laugh) {    if (ch = = ' h ')        console.write ("H");    else        console.write (CH);} Console.WriteLine ();   

Unsigned Data Type

In general, use int rather than unsigned types. The use of an int is common throughout C #, and it is easier to interact with other libraries when you use Int.

Arrays

Use the concise syntax if you initialize arrays on the declaration line.

Preferred syntax. Note that you cannot the use var here instead of string[].string[] vowels1 = {"A", "E", "I", "O", "U" };//If Your use exp  Licit instantiation, you can use Var.var VOWELS2 = new string[] {"A", "E", "I", "O", "U" };//If you specify an array Size, must initialize the elements one at a time.var VOWELS3 = new String[5];vowels3[0] = "a"; vowels3[1] = "E ";

Delegates

Use the concise syntax to create instances of a delegate type.

First, in class program, define the delegate type and a method,  //have a matching signature.//define the type. public delegate void Del (string message);//Define a method that has a matching signature.public static void Delmethod (String str) {    Console.WriteLine ("Delmethod argument: {0}", str);}  
In the Main method, create a instance of del.//Preferred:create an instance of Del by using condensed syntax. Del ExampleDel2 = delmethod;//The following declaration uses the full syntax. Del exampleDel1 = new del (delmethod);

Try-catch and using statements in Exception handling

Use a Try-catch statement for most exception handling.

static string Getvaluefromarray (string[] array, int index) {    try    {        return Array[index];    }    Catch (System.IndexOutOfRangeException ex)    {        Console.WriteLine ("Index is out of range: {0}", index );        Throw;}}     

Simplify your code by using the C # using statement. If you had a try-finally statement in which the only code in the finally block was a call to the Dispose method, use a USI NG statement instead.

This try-finally statement only calls Dispose in the finally block. Font font1 = new Font ("Arial", 10.0f); try{    byte charset = font1. gdiCharSet;} Finally{    if (font1! = null)    {        ((IDisposable) font1). Dispose ();    }} You can does the same thing with a using statement.using (font font2 = new Font ("Arial", 10.0f)) {byte CharSet =
         
           Font2. gdiCharSet;} 
              

&& | | Operators

To avoid exceptions and increase performance by skipping unnecessary comparisons, use && instead of & and | | instead of | When your perform comparisons, as shown in the following example.

Console.Write ("Enter A dividend:"), var dividend = convert.toint32 (Console.ReadLine ()); Console.Write ("Enter a divisor:"), var divisor = Convert.ToInt32 (Console.ReadLine ());/If The divisor is 0, the S Econd clause in the following condition//causes a run-time error. The && operator short circuits if the//first expression is false. That's, it does not evaluate the//second expression. The & operator evaluates both, and causes//a run-time error when divisor is 0.if ((divisor! = 0) && (dividen D/divisor > 0)) {    Console.WriteLine ("Quotient: {0}", dividend/ divisor);} Else{Console.WriteLine ("Attempted division by 0 ends up here." );}

New Operator

Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.

var Instance1 = new ExampleClass ();

The previous line was equivalent to the following declaration.

ExampleClass Instance2 = new ExampleClass ();

Use the object initializers to simplify object creation.

Object Initializer.var instance3 = new ExampleClass {Name = ' Desktop ', ID = 37414, location     = ' Redmond ', age = 2.3 };//Default constructor and assignment Statements.var Instance4 = new ExampleClass (); Instance4. Name = "Desktop"; instance4.id = 37414; instance4. Location = "Redmond"; Instance4. Age = 2.3;     

Event Handling

If You is defining an event handler so do not need to remove later, use a lambda expression.

Public Form2 () {    //can use a lambda expression to define an event handler.    This. Click + = (s, e) = =        {            MessageBox.Show ((                (MouseEventArgs) e). Location.tostring ());        };} 
Using a lambda expression shortens the following traditional definition.public Form1 () {this    . Click + = new EventHandler (Form1_Click);} void Form1_Click (Object sender, EventArgs e) {    MessageBox.Show (((MouseEventArgs) e). Location.tostring ());}  

Static Members

Call static members by using the class name: classname.staticmember. This practice makes code more readable by making static access clear. Do not qualify a static member defined in a base class with the name of a derived class. While this code compiles, the code readability is misleading, and the code could break in the future if you add a static mem ber with the same name to the derived class.

LINQ Queries

Use meaningful names for query variables. The following example uses seattlecustomers for customers who is located in Seattle.

var seattlecustomers = from Cust in customers                       where Cust. City = = "Seattle"                       Select Cust. Name;

Use the aliases to make sure this property names of anonymous types is correctly capitalized, using Pascal casing.

var localdistributors = from    customer in customers    joins distributor in distributors on customer. City equals Distributor. City    Select New {customer = customer, distributor = distributor}; 

Rename properties When "names in the" result would be ambiguous. For example, if your query returns a customer name and a Distributor ID, instead of leaving them as name and ID in The result, rename them to clarify , was the name of the customer, and Idis the ID of a distributor.

var localDistributors2 = from    Cust in customers    joins Dist in distributors on Cust. City equals Dist. City    Select New {CustomerName = cust. Name, Distributorid = dist.id}; 

Use implicit typing in the declaration of query variables and range variables.

var seattlecustomers = from Cust in customers                       where Cust. City = = "Seattle"                       Select Cust. Name;

Align query clauses under the FROM clause, as shown in the previous examples.

Use WHERE clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of Da Ta.

var seattleCustomers2 = from Cust in customers                        where Cust. City = = "Seattle" by the                         Cust. Name                        Select Cust; 

Use multiple from clauses instead of a joins clause to access inner collections. For example, a collection of Student objects might each contain a collection of test scores. When the following query was executed, it returns each score that's over, along with the last name of the student who R Eceived the score.

Use a compound from to access the inner sequence within each element.var Scorequery = from student in students                 From score in student. Scores                 where score >                 select new {last = student. LastName, score}; 
Naming conventions

Word Choice

? Do choose easily readable identifier names.

For example, the A property named HorizontalAlignment are more english-readable than alignmenthorizontal.

? Do favor readability over brevity.

The property name Canscrollhorizontally was better than Scrollablex (an obscure reference to the x-axis).

X does not use underscores, hyphens, or any other nonalphanumeric characters.

X do not use Hungarian notation.

X AVOID using identifiers that conflict with keywords of widely used programming languages.

Using Abbreviations and acronyms

X does not use the abbreviations or contractions as part of identifier names.

For example, use GetWindow rather than Getwin.

X do not use any acronyms that is not widely accepted, and even if they is, only when necessary

Avoiding Language-specific Names

? Do the semantically interesting names rather than language-specific keywords for type names.

For example, GetLength is a better name than GetInt.

? Do use a generic CLR type name, rather than a language-specific name, in the rare cases when an identifier have no semantic Meaning beyond its type.

For example, a method converting to Int64 should being named ToInt64, not Tolong (because Int64 are a CLR name for the C#-spec Ific alias Long). The following table presents several base data types using the CLR type names (as well as the corresponding type names for C #, Visual Basic, and C + +).

C # Coding & Naming conventions

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.