You are on page 1of 17

C# Coding Style Guide

Table Of Contents
1 About the C# Coding Style Guide.......................................................................................................2 2 File Organization.................................................................................................................................2 C Sourcefiles...................................................................................................................................2 Directory Layout.................................................................................................................................2 !ndentation........................................................................................................................................... 1

"ra##ing Lines................................................................................................................................... "hite S#aces....................................................................................................................................... $ Co%%ents............................................................................................................................................$ &loc' Co%%ents.................................................................................................................................$ Single Line Co%%ents........................................................................................................................$ Docu%entation Co%%ents..................................................................................................................$ ( Declarations.........................................................................................................................................( )u%ber of Declarations #er Line........................................................................................................( !nitialization........................................................................................................................................( Class and !nterface Declarations.........................................................................................................( * State%ents...........................................................................................................................................* Si%#le State%ents...............................................................................................................................* +eturn State%ents...............................................................................................................................* !f, if-else, if else-if else State%ents.....................................................................................................* For . Foreach State%ents...................................................................................................................../ "hile.do-0hile State%ents................................................................................................................./ S0itch State%ents.............................................................................................................................../ 1ry-catch State%ents...........................................................................................................................2 / "hite S#ace.........................................................................................................................................2 &lan' Lines.........................................................................................................................................2 !nter-ter% s#acing...............................................................................................................................3 1able li'e for%atting...........................................................................................................................3 2 )a%ing Con4entions ..........................................................................................................................3 Ca#italization Styles Defined .............................................................................................................3 5ungarian 1y#e )otation Defined ...................................................................................................16 )a%ing Guidelines ..........................................................................................................................16 3 7rogra%%ing 7ractices......................................................................................................................1$ 8isibility............................................................................................................................................1( )o 9%agic9 )u%bers..........................................................................................................................1( 16 Code :;a%#les................................................................................................................................1( &race #lace%ent e;a%#le.................................................................................................................1( 8ariable na%ing e;a%#le.................................................................................................................1*

1 About the C# Coding Style Guide


1his docu%ent %ay be read as a guide to 0riting robust and reliable #rogra%s. !t focuses on #rogra%s 0ritten in C , but %any of the rules and #rinci#les are useful e4en if you 0rite in another #rogra%%ing language.

2 File Organization
C Sourcefiles
<ee# your classes.files short, don9t e;ceed 2666 LOC, di4ide your code u#, %a'e structures clearer. 7ut e4ery class in a se#arate file and na%e the file li'e the class na%e =0ith .cs as e;tension of course>. 1his con4ention %a'es things %uch easier.

Directory Layout
Create a directory for e4ery na%es#ace. =For MyProject.TestSuite.TestTier use MyProject/

TestSuite/TestTier as the #ath, do not use the na%es#ace na%e 0ith dots.> 1his %a'es it easier to %a# na%es#aces to the directory layout.

!ndentation
"ra##ing Lines
"hen an e;#ression 0ill not fit on a single line, brea' it u# according to these general #rinci#les? &rea' after a co%%a. &rea' after an o#erator. 7refer higher-le4el brea's to lo0er-le4el brea's. Align the ne0 line 0ith the beginning of the e;#ression at the sa%e le4el on the #re4ious line

:;a%#le of brea'ing u# %ethod calls? longMethodCall(expr1, expr2, expr3, expr4, expr5); :;a%#les of brea'ing an arith%etic e;#ression? 7+:F:+? var = a * b / (c - g + f) + 4 * z; &AD S1@L: A A8O!D? var = a * b / (c - g + f) + 4 * z; 1he first is #referred, since the brea' occurs outside the #arenthesized e;#ression =higher le4el rule>. )ote that you indent 0ith tabs to the indentation le4el and then 0ith s#aces to the brea'ing #osition in our e;a%#le this 0ould be? > > var = a * b / (c - g + f) + ......4 * z;

"here 9B9 are tab chars and 9.9 are s#aces. =the s#aces after the tab char are the indent 0ith of the tab>. A good coding #ractice is to %a'e the tab and s#ace chars 4isible in the editor 0hich is used.

"hite S#aces
An indentation standard using s#aces ne4er 0as achie4ed. So%e #eo#le li'e 2 s#aces, so%e #refer $ and others die for 2, or e4en %ore s#aces. &etter use tabs. 1ab characters ha4e so%e ad4antages? :4eryone can set their o0n #referred indentation le4el !t is only 1 character and not 2, $, 2 C therefore it 0ill reduce ty#ing =e4en 0ith s%artindenting you ha4e to set the indentation %anually so%eti%es, or ta'e it bac' or 0hate4er> !f you 0ant to increase the indentation =or decrease>, %ar' one bloc' and increase the indent le4el 0ith 1ab 0ith Shift-1ab you decrease the indentation. 1his is true for al%ost any te;teditor.

5ere, 0e define the 1ab as the standard indentation character.

Don't use spaces for indentation - use tabs!

$ Co%%ents
&loc' Co%%ents
&loc' co%%ents should usually be a4oided. For descri#tions use of the ... co%%ents to gi4e C standard descri#tions is reco%%ended. "hen you 0ish to use bloc' co%%ents you should use the follo0ing style ? /* Line 1 * Line 2 * Line 3 */ As this 0ill set off the bloc' 4isually fro% code for the =hu%an> reader. Alternati4ely you %ight use this oldfashioned C style for single line co%%ents, e4en though it is not reco%%ended. !n case you use this style, a line brea' should follo0 the co%%ent, as it is hard to see code #receeded by co%%ents in the sa%e line? /* blah blah blah */ &loc' co%%ents %ay be useful in rare cases, refer to the 1ech)ote 91he fine Art of Co%%enting9 for an e;a%#le. Generally bloc' co%%ents are useful for co%%ent out large sections of code.

Single Line Co%%ents


@ou should use the .. co%%ent style to Dco%%ent outD code =Shar#De4elo# has a 'ey for it, AltE.> . !t %ay be used for co%%enting sections of code too. Single line co%%ents %ust be indented to the indent le4el 0hen they are used for code docu%entation. Co%%ented out code should be co%%ented out in the first line to enhance the 4isibility of co%%ented out code. A rule of thu%b says that generally, the length of a co%%ent should not e;ceed the length of the code e;#lained by too %uch, as this is an indication of too co%#licated, #otentially buggy, code.

Docu%entation Co%%ents
!n the .net fra%e0or', Ficrosoft has introduced a docu%entation generation syste% based on GFL co%%ents. 1hese co%%ents are for%ally single line C co%%ents containing GFL tags. 1hey follo0 this #attern for single line co%%ents? /// <summary> /// This class... /// </summary> Fultiline GFL co%%ents follo0 this #attern? /// /// /// /// <exception cref=BogusException> This exception gets thrown as soon as a Bogus flag gets set. </exception>

All lines %ust be #receded by three slashes to be acce#ted as GFL co%%ent lines. 1ags fall into t0o categories? Docu%entation ite%s

For%atting.+eferencing

1he first category contains tags li'e <summary>, <param> or <exception>. 1hese re#resent ite%s that re#resent the ele%ents of a #rogra%9s A7! 0hich %ust be docu%ented for the #rogra% to be useful to other #rogra%%ers. 1hese tags usually ha4e attributes such as name or cref as de%onstrated in the

%ultiline e;a%#le abo4e. 1hese attributes are chec'ed by the co%#iler, so they should be 4alid. 1he latter category go4erns the layout of the docu%entation, using tags such as <code>, <list> or <para>.
Docu%entation can then be generated using the 9docu%entation9 ite% in the #de4elo# 9build9 %enu. 1he docu%entation generated is in 51FL5el# for%at. For a fuller e;#lanation of GFL co%%ents see the Ficrosoft .net fra%e0or' SD< docu%entation. For infor%ation on co%%enting best #ractice and further issues related to co%%enting, see the 1ech)ote 91he fine Art of Co%%enting9.

( Declarations
)u%ber of Declarations #er Line
One declaration #er line is reco%%ended since it encourages co%%enting1. !n other 0ords, int level; // indentation level int size; // size of table Do not #ut %ore than one 4ariable or 4ariables of different ty#es on the sa%e line 0hen declaring the%. :;a%#le? int a, b; //What is 'a'? What does 'b' stand for? 1he abo4e e;a%#le also de%onstrates the dra0bac's of non-ob4ious 4ariable na%es. &e clear 0hen na%ing 4ariables.

!nitialization
1ry to initialize local 4ariables as soon as they are declared. For e;a%#le? string name = myObject.Name;

or
int val = time.Hours;

)ote? !f you initialize a dialog try to use the using state%ent? using (OpenFileDialog openFileDialog = new OpenFileDialog()) { ... }

Class and !nterface Declarations


"hen coding C classes and interfaces, the follo0ing for%atting rules should be follo0ed?

)o s#ace bet0een a %ethod na%e and the #arenthesis D(D starting its #ara%eter list. 1he o#ening brace D{D a##ears in the ne;t line after the declaration state%ent. 1he closing brace D }D starts a line by itself indented to %atch its corres#onding o#ening brace.

For e;a%#le ? class MySample : MyClass, IMyInterface { int myInt;


1 Of course, using self-e;#lanatory 4ariable na%es such as indentLevel %a'e these co%%ents obsolete.

public MySample(int myInt) { this.myInt = myInt ; } void Inc() { ++myInt; } void EmptyMethod() { } } For a brace #lace%ent e;a%#le loo' at section 16.1.

* State%ents
Si%#le State%ents
:ach line should contain only one state%ent.

+eturn State%ents
A return state%ent should not use outer %ost #arentheses. Don9t use ? return (n * (n + 1) / 2); use ? return n * (n + 1) / 2;

!f, if-else, if else-if else State%ents


if, if-else and if else-if else state%ents should loo' li'e this? if (condition) { DoSomething() ... } if (condition) { DoSomething(); ... } else { DoSomethingOther(); ... }

if (condition) { DoSomething(); ... } else if (condition) { DoSomethingOther(); ... } else { DoSomethingOtherAgain(); ... }

For . Foreach State%ents


A for state%ent shoud ha4e follo0ing for% ? for (int i = 0; i < 5; ++i) { ... } or single lined =consider using a 0hile state%ent instead> ? for (initialization; condition; update) ; A foreach should loo' li'e ? foreach (int i in IntList) { ... } )ote? Generally use brac'ets e4en if there is only one state%ent in the loo#.

"hile.do-/hile State%ents
A while state%ent should be 0ritten as follo0s? while (condition) { ... } An e%#ty while should ha4e the follo0ing for%? while (condition) ; A do-while state%ent should ha4e the follo0ing for%? do { ... } while (condition);

S/itch State%ents
A switch state%ent should be of follo0ing for%? switch (condition) { case A: ... break;

case B: ... break; default: ... break; }

Try-catch State%ents
A try-catch state%ent should follo0 this for%? try { ... } catch (Exception) {}

Or
try { ... } catch (Exception e) { ... } Or try { ... } catch (Exception e) { ... } finally { ... }

0 "hite S#ace
&lan' Lines
&lan' lines i%#ro4e readability. 1hey set off bloc's of code 0hich are in the%sel4es logically related. 10o blan' lines should al0ays be used bet0een? Logical sections of a source file Class and interface definitions =try one class.interface #er file to #re4ent this case>

One blan' line should al0ays be used bet0een? Fethods 7ro#erties Local 4ariables in a %ethod and its first state%ent Logical sections inside a %ethod to i%#ro4e readability

)ote that blan' lines %ust be indented as they 0ould contain a state%ent this %a'es insertion in these lines %uch easier.

!nter-ter% s#acing
1here should be a single s#ace after a co%%a or a se%icolon, for e;a%#le? TestMethod(a, b, c); don't use : TestMethod(a,b,c) or TestMethod( a, b, c );

Single s#aces surround o#erators =e;ce#t unary o#erators li'e incre%ent or logical not>, e;a%#le? a = b; // don't use a=b; for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i) // or // for(int i=0;i<10;++i)

Table li'e for%atting


A logical bloc' of lines should be for%atted as a table? string name = "Mr. Ed"; int myValue = 5; Test aTest = Test.TestYou; Hse s#aces for the table li'e for%atting and not tabs because the table for%atting %ay loo' strange in s#ecial tab intent le4els.

1 )a%ing Con2entions
A consistent na%ing #attern is one of the %ost i%#ortant ele%ents of #redictability and disco4erability in a %anaged class library. "ides#read use and understanding of these na%ing guidelines should eli%inate unclear code and %a'e it easier for de4elo#ers to understand shared code.

Ca#italization Styles Defined


"e define three ty#es of ca#italization styles? Pascal case 1he first letter in the identifier and the first letter of each subseIuent concatenated 0ord are ca#italized. :;a%#le? BackColor, DataSet Camel case 1he first letter of an identifier is lo0ercase and the first letter of each subseIuent concatenated 0ord is ca#italized. :;a%#le? numberOfDays, isValid Uppercase All letters in the identifier are ca#italized.

:;a%#le? D, P

3ungarian Ty#e )otation Defined


5ungarian notation is any of a 4ariety of standards for organizing a co%#uter #rogra% by selecting a sche%a for na%ing your 4ariables so that their ty#e is readily a4ailable to so%eone fa%iliar 0ith the notation. !t is in fact a co%%enting techniIue. :;a%#le? str!irst"ame, i"umberOfDays 1here are different o#inions about using this 'ind of ty#e notation in #rogra%%ing no0adays. So%e say that itJs useful, and it should be used e4ery0here to enhance clarity of your code. Others say it Kust obfuscates your code, because it has no real ad4antage in %odern #rogra%%ing en4iron%ents. Our #oint of 4ie0 is a %oderated one? use it 0isely, %eaning, 0e only use 5ungarian notation for pri#ate or local #ariables, that are only accessible and interesting to the #rogra%%er of the class. Don$t use it %it& public 4ariables, #ro#erties or #ara%eters in %ethods, because they are e;#osed to the outside 0orld. So%eone 0ho uses your classes and accesses #ro#erties of your class, is not interested in ty#e, but Kust 0ants to use the%. !n the .):1 fra%e0or', there are a lot of ty#es, so 0e e;tended and ada#ted the 5ungarian notation 0ith our o0n ty#e notation.

)a%ing Guidelines 8.3.1 4ri2ate 5ariables 6Fields in C#7 )a%ing Guidelines


"amin' 'uidelines 7refi; #ri4ate 4ariables 0ith a DLD and 5ungarian-style notation. Case 'uidelines Hse ca%el case as a general rule, or u##ercase for 4ery s%all 0ords :;a%#le? (str!irst"ame, (dset)mployees .. Field #ri4ate OleDbConnection (connectionM .. 7ro#erty #ublic OleDbConnection Connection N get N return (connectionM O set N (connection P 4alueM O O

16

8.3.2 Local 5ariables )a%ing Guidelines


"amin' 'uidelines 7refi; #ri4ate or local 4ariables 0ith 5ungarian-style notation. Case 'uidelines Hse ca%el case as a general rule, or u##ercase for 4ery s%all 0ords :;a%#le? str!irst"ame, dset)mployees

8.3.3 )a%es#ace )a%ing Guidelines


"amin' 'uidelines 1he general rule for na%ing na%es#aces is to use the co%#any na%e follo0ed by the technology na%e and o#tionally the feature and design as follo0s? Company"ame*+ec&nolo'y"ame,*!eature-,*Desi'n7refi;ing na%es#ace na%es 0ith a co%#any na%e or other 0ell-established brand a4oids the #ossibility of t0o #ublished na%es#aces ha4ing the sa%e na%e. Hse a stable, recognized technology na%e at the second le4el of a hierarchical na%e. :;a%#le? .kadia*+raffic, System*/eb*U , System*/indo%s*!orms Case 'uidelines Hse 7ascal case as a general rule, or u##ercase for 4ery s%all 0ords. :;a%#le? System*/indo%s*!orms, System*/eb*U

8.3.4 Class )a%ing Guidelines


"amin' 'uidelines Hse a noun or noun #hrase to na%e a class. Do not use a ty#e #refi;, such as C for class, on a class na%e. Do not use the underscore character =L>. Case 'uidelines Hse 7ascal case. :;a%#le? !ileStream, Button

8.3.5 !nterface )a%ing Guidelines


"amin' 'uidelines 7refi; interface na%es 0ith the letter D!D, to indicate that the ty#e is an interface. Do not use the underscore character =L>.

11

Case 'uidelines Hse 7ascal case. :;a%#le? Ser#icePro#ider, !ormatable

8.3.6 4ara%eter )a%ing Guidelines


"amin' 'uidelines Hse descri#ti4e #ara%eter na%es. 7ara%eter na%es should be descri#ti4e enough that the na%e of the #ara%eter and its ty#e can be used to deter%ine its %eaning in %ost scenarios. 1o distinguish #ara%eters fro% other 4ariables the #refi; 0p0 should be used. Do not #refi; #ara%eter na%es 0ith 5ungarian ty#e notation. Do not use a #refi; for #ara%eter na%es of an e4ent handler and e;ce#tions. Case 'uidelines Hse ca%el case. :;a%#le? p+ype"ame, p"umberOf tems

8.3.7 8ethod )a%ing Guidelines


"amin' 'uidelines Hse 4erbs or 4erb #hrases to na%e %ethods. Case 'uidelines Hse 7ascal case. :;a%#le? 1emo#e.ll23, 4etC&ar.t23

8.3.8 4ro#erty . 9nu%erations )a%ing Guidelines


"amin' 'uidelines Hse a noun or noun #hrase to na%e #ro#erties. Do not use 5ungarian notation. Case 'uidelines Hse 7ascal case. :;a%#le? BackColor, "umberOf tems

8.3.9 92ent )a%ing Guidelines


"amin' 'uidelines Hse an :4ent5andler suffi; on e4ent handler na%es. S#ecify t0o #ara%eters na%ed sender and e. 1he sender #ara%eter re#resents the obKect that raised the e4ent. 1he sender #ara%eter is al0ays of ty#e obKect, e4en if it is #ossible to use a %ore s#ecific ty#e. 1he state

12

associated 0ith the e4ent is enca#sulated in an instance of an e4ent class na%ed 0e0. Hse an a##ro#riate and s#ecific e4ent class for the e #ara%eter ty#e. )a%e an e4ent argu%ent class 0ith the )#ent.r's suffi;. Case 'uidelines Hse 7ascal case. :;a%#le? public dele'ate #oid 5ouse)#ent6andler2ob7ect sender, 5ouse)#ent.r's e38

8.3.10
"amin' 'uidelines

9:ce#tion )a%ing Guidelines

:4ent handlers in 8isual Studio .):1 tend to use an DeD #ara%eter for the e4ent #ara%eter to the call. 1o ensure 0e a4oid a conflict, 0e 0ill use De9D as a standard 4ariable na%e for an :;ce#tion obKect. :;a%#le catch =:;ce#tion e9> N .. 5andle :;ce#tion O

8.3.11

Constant )a%ing Guidelines

1he na%es of 4ariables declared class constants should be all u##ercase 0ith 0ords se#arated by underscores. !t is reco%%ended to use a grou#ing na%ing sche%a. :;a%#le =for grou# A7L"!)>? .P(/ "(5 "(/ D+6, .P(/ "(5.:(/ D+6, .P(/ "(5 "(6 46+, .P(/ "(5.:(6 46+

8.3.12
sbyte sy short s int i long l byte y ushort us uint ui ulong ul float f double d deci%al dec bool b char c

C# 4ri%iti2e Ty#e )otation

8.3.13
Asse%bly &oolean &utton Char

5isual Control Ty#e )otation


as% bln btn ch

Chec'&o; Co%bo&o; Container DataColu%n DataGrid DataGridDate1i%e7ic'erColu%n DataGrid1ableStyle DataGrid1e;t&o;Colu%n Data+eader Data+o0 DataSet Data1able Date1i%e Dialog Dialog+esult Double :;ce#tion Grou#&o; 5ash1able !%ageList !nteger Label List&o; List8ie0 Farshall&y+efObKect Fain%enu Fenu!te% FD!-Fra%e FD!-Sheet )u%ericH#Do0n 7anel 7icture&o; +adio&utton SD!-For% SIlCo%%and SIlCo%%and&uilder SIlConnection SIlDataAda#ter Status&ar String String&uilder 1abControl 1ab7age 1e;t&o; 1ool&ar 1ool&ar&utton 1i%er HserControl "indo0s7rinci#al

cb; c%b ctr dcol dgrid dgdt#c dgts dgtbc dreader dro0 dset dtable date dialog dr dbl e; gb; htbl i%l int lbl lb; l4 r%t %% %i fra%e sheet nud #nl #b; rbtn for% sIlco% sIlco%b sIlcon sIlda stb str strb tabctrl tab#age tb; tbr tbb t%r usr 0#l

; 4rogra%%ing 4ractices

1$

5isibility
Do not %a'e any instance or class 4ariable public, %a'e the% private. For #ri4ate %e%bers #refer not using private as %odifier Kust do 0rite nothing. 7ri4ate is the default case and e4ery C #rogra%%er should be a0are of it. Hse #ro#erties instead. @ou %ay use public static fields =or const) as an e;ce#tion to this rule, but it should not be the rule.

)o <%agic< )u%bers
DonJt use %agic nu%bers, i.e. #lace constant nu%erical 4alues directly into the source code. +e#lacing these later on in case of changes =say, your a##lication can no0 handle ($6 users instead of the $2/ hardcoded into your code in (6 lines scattered troughout your 2(666 LOC> is error-#rone and un#roducti4e. !nstead declare a const 4ariable 0hich contains the nu%ber ? public class MyMath { public const double PI = 3.14159... }

1=Code 9:a%#les
&race #lace%ent e:a%#le
namespace ShowMeTheBracket { public enum Test { TestMe, TestYou } public class TestMeClass { Test test; public Test Test { get { return test; } set { test = value; } } void DoSomething() { if (test == Test.TestMe) { //...stuff gets done } else { //...other stuff gets done } } } } &rac'ets should begin on a ne0 line only after?

1(

)a%es#ace declarations =note that this is ne0 in 4ersion 6. and 0as different in 6.2> Class.!nterface.Struct declarations Fethod declarations

5ariable na%ing e:a%#le


instead of ? for (int i = 1; i < num; ++i) { meetsCriteria[i] = true; } for (int i = 2; i < num / 2; ++i) { int j = i + i; while (j <= num) { meetsCriteria[j] = false; j += i; } } for (int i = 0; i < num; ++i) { if (meetsCriteria[i]) { Console.WriteLine(i + " meets criteria"); } } try intelligent na%ing ? for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate) { isPrime[primeCandidate] = true; } for (int factor = 2; factor < num / int factorableNumber = factor + while (factorableNumber <= num) isPrime[factorableNumber] = factorableNumber += factor; } } 2; ++factor) { factor; { false;

for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate) { if (isPrime[primeCandidate]) { Console.WriteLine(primeCandidate + " is prime."); } } "ote; !nde;er 4ariables generally should be called i,j,k etc. &ut in cases li'e this, it %ay %a'e sense to reconsider this rule. !n general, 0hen the sa%e counters or inde;ers are reused, gi4e the% %eaningful na%es.

1*

1/