C# Coding Conventions (C# Programming Guide)
C# Coding Conventions (C# Programming Guide)
C# Coding Conventions (C# Programming Guide)
C#CodingConventions(C#ProgrammingGuide)
The C# Language Specification does not define a coding standard. However, the guidelines in this topic are used by
Microsoft to develop samples and documentation.
Coding conventions serve the following purposes:
They create a consistent look to the code, so that readers can focus on content, not layout.
They enable readers to understand the code more quickly by making assumptions based on previous
experience.
They facilitate copying, changing, and maintaining the code.
They demonstrate C# best practices.
Naming Conventions
In short examples that do not include using directives, use namespace qualifications. If you know that a
namespace is imported by default in a project, you do not have to fully qualify the names from that
namespace. Qualified names can be broken after a dot . if they are too long for a single line, as shown in
the following example.
C#
varcurrentPerformanceCounterCategory=newSystem.Diagnostics.
PerformanceCounterCategory();
You do not have to change the names of objects that were created by using the Visual Studio designer
tools to make them fit other guidelines.
Layout Conventions
Good layout uses formatting to emphasize the structure of your code and to make the code easier to read.
Microsoft examples and samples conform to the following conventions:
Use the default Code Editor settings smart indenting, fourcharacter indents, tabs saved as spaces. For
more information, see Options, Text Editor, C#, Formatting.
Write only one statement per line.
https://msdn.microsoft.com/enus/library/ff926074.aspx
1/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
Commenting 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.
C#
//Thefollowingdeclarationcreatesaquery.Itdoesnotrun
//thequery.
Do not create formatted blocks of asterisks around comments.
Language Guidelines
The following sections describe practices that the C# team follows to prepare code examples and samples.
2/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
StringBuilder object.
C#
varphrase="lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
varmanyPhrases=newStringBuilder();
for(vari=0;i<10000;i++)
{
manyPhrases.Append(phrase);
}
//Console.WriteLine("tra"+manyPhrases);
https://msdn.microsoft.com/enus/library/ff926074.aspx
3/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
varsyllable="ha";
varlaugh="";
for(vari=0;i<10;i++)
{
laugh+=syllable;
Console.WriteLine(laugh);
}
The following example uses implicit typing in a foreach statement.
C#
foreach(varchinlaugh)
{
if(ch=='h')
Console.Write("H");
else
Console.Write(ch);
}
Console.WriteLine();
Arrays
Use the concise syntax when you initialize arrays on the declaration line.
C#
//Preferredsyntax.Notethatyoucannotusevarhereinsteadofstring[].
string[]vowels1={"a","e","i","o","u"};
//Ifyouuseexplicitinstantiation,youcanusevar.
varvowels2=newstring[]{"a","e","i","o","u"};
//Ifyouspecifyanarraysize,youmustinitializetheelementsoneatatime.
varvowels3=newstring[5];
vowels3[0]="a";
vowels3[1]="e";
//Andsoon.
https://msdn.microsoft.com/enus/library/ff926074.aspx
4/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
Delegates
Use the concise syntax to create instances of a delegate type.
C#
//First,inclassProgram,definethedelegatetypeandamethodthat
//hasamatchingsignature.
//Definethetype.
publicdelegatevoidDel(stringmessage);
//Defineamethodthathasamatchingsignature.
publicstaticvoidDelMethod(stringstr)
{
Console.WriteLine("DelMethodargument:{0}",str);
}
C#
//IntheMainmethod,createaninstanceofDel.
//Preferred:CreateaninstanceofDelbyusingcondensedsyntax.
DelexampleDel2=DelMethod;
//Thefollowingdeclarationusesthefullsyntax.
DelexampleDel1=newDel(DelMethod);
5/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
C#
//ThistryfinallystatementonlycallsDisposeinthefinallyblock.
Fontfont1=newFont("Arial",10.0f);
try
{
bytecharset=font1.GdiCharSet;
}
finally
{
if(font1!=null)
{
((IDisposable)font1).Dispose();
}
}
//Youcandothesamethingwithausingstatement.
using(Fontfont2=newFont("Arial",10.0f))
{
bytecharset=font2.GdiCharSet;
}
New Operator
https://msdn.microsoft.com/enus/library/ff926074.aspx
6/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.
C#
varinstance1=newExampleClass();
The previous line is equivalent to the following declaration.
C#
ExampleClassinstance2=newExampleClass();
Use object initializers to simplify object creation.
C#
//Objectinitializer.
varinstance3=newExampleClass{Name="Desktop",ID=37414,
Location="Redmond",Age=2.3};
//Defaultconstructorandassignmentstatements.
varinstance4=newExampleClass();
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.
C#
publicForm2()
{
//Youcanusealambdaexpressiontodefineaneventhandler.
this.Click+=(s,e)=>
{
MessageBox.Show(
((MouseEventArgs)e).Location.ToString());
};
}
C#
//Usingalambdaexpressionshortensthefollowingtraditionaldefinition.
publicForm1()
{
this.Click+=newEventHandler(Form1_Click);
https://msdn.microsoft.com/enus/library/ff926074.aspx
7/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
}
voidForm1_Click(objectsender,EventArgse)
{
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.
C#
varseattleCustomers=fromcustincustomers
wherecust.City=="Seattle"
selectcust.Name;
Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal
casing.
C#
varlocalDistributors=
fromcustomerincustomers
joindistributorindistributorsoncustomer.Cityequalsdistributor.City
selectnew{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 ID is the ID of a distributor.
C#
varlocalDistributors2=
fromcustincustomers
joindistindistributorsoncust.Cityequalsdist.City
selectnew{CustomerName=cust.Name,DistributorID=dist.ID};
https://msdn.microsoft.com/enus/library/ff926074.aspx
8/9
12/9/2015
C#CodingConventions(C#ProgrammingGuide)
Use implicit typing in the declaration of query variables and range variables.
C#
varseattleCustomers=fromcustincustomers
wherecust.City=="Seattle"
selectcust.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.
C#
varseattleCustomers2=fromcustincustomers
wherecust.City=="Seattle"
orderbycust.Name
selectcust;
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.
C#
//Useacompoundfromtoaccesstheinnersequencewithineachelement.
varscoreQuery=fromstudentinstudents
fromscoreinstudent.Scores
wherescore>90
selectnew{Last=student.LastName,score};
Security
Follow the guidelines in Secure Coding Guidelines.
See Also
Visual Basic Coding Conventions
Secure Coding Guidelines
2015 Microsoft
https://msdn.microsoft.com/enus/library/ff926074.aspx
9/9