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 are 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 an expression apparent, as shown in the following code.

if ((val1 > val2) && (val1 > val3))
{
  // Take appropriate action.
}

Comment Conventions

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

Begin comment text with an 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 when you are 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 is obvious from the right side of the assignment, or when the precise type is not important.

var var1 = "This is clearly a string.";
var var2 = 27;
var var3 = Convert.ToInt32(Console.ReadLine());

Do not use var when the type is not apparent from the right side of the assignment.

// When the type of a variable is not clear from the context, use an explicit type.
int var4 = ExampleClass.ResultSoFar();

Do not rely on the variable name to specify the type of the variable. It might not be 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 int is common throughout C#, and it is easier to interact with other libraries when you use int.

Arrays

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

// Preferred syntax. Note that you cannot use var here instead of string[].
string[] vowels1 = { "a", "e", "i", "o", "u" }; // If you use explicit instantiation, you can use var.
var vowels2 = new string[] { "a", "e", "i", "o", "u" }; // If you specify an array size, you 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 that
// has 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 an 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 have a try-finally statement in which the only code in the finally block is a call to the Dispose method, use a using 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 do the same thing with a using statement.
using (Font font2 = new Font("Arial", 10.0f))
{
byte charset = font2.GdiCharSet;
}

&& and || Operators

To avoid exceptions and increase performance by skipping unnecessary comparisons, use && instead of & and || instead of | when you 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 second clause in the following condition
// causes a run-time error. The && operator short circuits when the
// first expression is false. That is, it does not evaluate the
// second expression. The & operator evaluates both, and causes
// a run-time error when divisor is 0.
if ((divisor != 0) && (dividend / 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 is equivalent to the following declaration.

ExampleClass instance2 = new ExampleClass();

Use 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 are defining an event handler that you do not need to remove later, use a lambda expression.

public Form2()
{
// You 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 that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.

LINQ Queries

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

var seattleCustomers = from cust in customers
where cust.City == "Seattle"
select cust.Name;

Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.

var localDistributors =
from customer in customers
join distributor in distributors on customer.City equals distributor.City
select new { Customer = customer, Distributor = distributor };

Rename properties when the property 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 that Name is the name of a customer, and IDis the ID of a distributor.

var localDistributors2 =
from cust in customers
join 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 data.

var seattleCustomers2 = from cust in customers
where cust.City == "Seattle"
orderby cust.Name
select cust;

Use multiple from clauses instead of a join clause to access inner collections. For example, a collection of Student objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received 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 > 90
select new { Last = student.LastName, score };

Naming Conventions

Word Choice

✓ DO choose easily readable identifier names.

For example, a property named HorizontalAlignment is more English-readable than AlignmentHorizontal.

✓ DO favor readability over brevity.

The property name CanScrollHorizontally is better than ScrollableX (an obscure reference to the X-axis).

X DO 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 DO NOT use abbreviations or contractions as part of identifier names.

For example, use GetWindow rather than GetWin.

X DO NOT use any acronyms that are not widely accepted, and even if they are, only when necessary

Avoiding Language-Specific Names

✓ DO use 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 has no semantic meaning beyond its type.

For example, a method converting to Int64 should be named ToInt64, not ToLong (because Int64 is a CLR name for the C#-specific 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的更多相关文章

  1. Effective Java 56 Adhere to generally accepted naming conventions

    Typographical naming conventions Identifier Type Type Examples Package com.google.inject, org.joda.t ...

  2. Naming Conventions for .NET / C# Projects

    http://www.akadia.com/services/naming_conventions.html Naming Conventions for .NET / C# Projects Mar ...

  3. Spring mvc 4系列教程(二)——依赖管理(Dependency Management)和命名规范(Naming Conventions)

    依赖管理(Dependency Management)和命名规范(Naming Conventions) 依赖管理和依赖注入(dependency injection)是有区别的.为了将Spring的 ...

  4. JavaScript Patterns 2.10 Naming Conventions

    1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the word ...

  5. Naming conventions of python

    1.package name 全部小写字母,中间可以由点分隔开,作为命名空间,包名应该具有唯一性,推荐采用公司或组织域名的倒置,如com.apple.quicktime.v2 2.module nam ...

  6. C# Coding Conventions(译)

    C# Coding Conventions C#编码规范 Naming Conventions 命名规范Layout Conventions 布局规范Commenting Conventions 注释 ...

  7. C# Coding Conventions, Coding Standards & Best Practices

    C# Coding Conventions, Coding Standards & Best Practices Cui, Chikun Overview Introduction This ...

  8. python coding style guide 的高速落地实践

    python coding style guide 的高速落地实践 机器和人各有所长,如coding style检查这样的可自己主动化的工作理应交给机器去完毕,故发此文帮助你在几分钟内实现coding ...

  9. 学习笔记之Coding / Design / Tool

    CODING 学习笔记之代码大全2 - 浩然119 - 博客园 https://www.cnblogs.com/pegasus923/p/5301123.html 学习笔记之编程珠玑 Programm ...

随机推荐

  1. Linux系统学习笔记之 1 基础命令

    翻看日记,看到以前自己学习Linux是的笔记来了,温故而知新乎.   文件命名规则: 1.除了/之外,所有的字符都合法. 2.有些字符最好不要用,如空格符.制表符.退格符.和@ # & ( ) ...

  2. bzoj 1088: [SCOI2005]扫雷Mine

    题目链接 1088: [SCOI2005]扫雷Mine Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 2525  Solved: 1495[Submi ...

  3. C语言负数的除法和求余运算

    假定我们让 a 除以 b,商为 q,余数为 r: q = a / b; r = a % b; 这里,不妨假定 b 大于 0. 我们希望 a.b.q.r 之间维持怎样的关系呢? 1.最重的一点,我们希望 ...

  4. DX9三角形顶点绕序的判断

    今天亲自实践了下,终于搞清楚了. 多边形都有2个侧面,观察坐标系中正面朝向摄像机的为多边形为正面朝向多边形,正面偏离摄像机的为多边形为背面朝向多边形,d3d会把背面朝向多边形剔除,即背面消隐. 使用 ...

  5. ThinkPHP 3 的输出

    一.ThinkPHP 3 的输出 (重点) a.通过 echo 等PHP原生的输出方式在页面中输出 b.通过display方法输出 想分配变量可以使用assign方法 c.修改左右定界符 休要修改配置 ...

  6. ubuntu12.04&15.04 安装lamp(12.04为主)

    ubuntu 12.04&15.04下安装lamp环境 注意:如果是ubuntu15.04下,apache2.4.10的话,直接在/etc/apache2/apache2.conf文件的后边直 ...

  7. PowerDesigner 基础使用

    建表使用基础 1.打开软件,点击create model(如下图一)or 右上角 文件→建立新模型 or 快捷键 Ctrl+N(如下图二) 2.选择要生成脚本的数据库类型(见上图二) 3.建表(图三) ...

  8. SQL Server索引进阶:第一级,索引简介

    这个并不是我翻译的,全文共有15篇,但我发现好多网站已经不全,所以自己整理. 原文地址: Stairway to SQL Server Indexes: Level 1, Introduction t ...

  9. BootStrap 智能表单系列 六 表单数据绑定(编辑页面的数据绑定)

    本章介绍如何在生成表单后,将一个model的数据展示到form表单中(一般用于编辑页面) 代码如下(连接地址:https://github.com/xiexingen/Bootstrap-SmartF ...

  10. ImageMagick 转换 progressive jpeg

    什么是渐进式图片(Progressive JPEG)? 来自 张鑫旭-鑫空间-鑫生活 的解释: 不知诸位有没有注意到,这些jpg格式的图片在呈现的时候,有两种方式,一种是自上而下扫描式的,还有一种就是 ...