This document provides style guidelines for C# coding, covering topics such as file organization, indentation, comments, declarations, statements, and white space. Key recommendations include putting each class in its own file with a matching name, using tabs for indentation rather than spaces, using single line or XML comments as appropriate, declaring one variable per line with descriptive names, and formatting if/else and other statements consistently. The goal is to write robust, reliable code according to standard conventions.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
98 views
Sharp Develop Coding Style 03
This document provides style guidelines for C# coding, covering topics such as file organization, indentation, comments, declarations, statements, and white space. Key recommendations include putting each class in its own file with a matching name, using tabs for indentation rather than spaces, using single line or XML comments as appropriate, declaring one variable per line with descriptive names, and formatting if/else and other statements consistently. The goal is to write robust, reliable code according to standard conventions.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13
Technotes, HowTo Series
C Coding Style Guide
Version 0.3 by Mike Krger, ike!icsh"r#code.net Contents 1 About the C# Coding Style Guide..................................................................................... 1 2 File Organization............................................................................................................... 1 3 Indentation........................................................................................................................ 2 4 Comments......................................................................................................................... 3 !e"larations...................................................................................................................... 4 # Statements........................................................................................................................ $ %hite S&a"e...................................................................................................................... $ ' (aming Con)entions......................................................................................................... * * +rogramming +ra"ti"es................................................................................................... 11 1, Code -.am&les............................................................................................................. 12 $ %bout the C& Coding Style Guide This document may be read as a guide to writing robust and reliable programs. It focuses on programs written in C , but many of the rules and principles are useful even if you write in another programming language. ' (ile )rg"ni*"tion 2.1 C Sour"e/iles Keep your classes/files short, don't exceed !!! "#C, divide your code up, ma$e structures clearer. %ut every class in a separate file and name the file li$e the class name &with .cs as extension of course'. This convention ma$es things much easier. 2.2 !ire"tory 0ayout Create a directory for every namespace. &(or MyProject.TestSuite.TestTier use MyProject/ TestSuite/TestTier as the path, do not use the namespace name with dots.' This ma$es it easier to map namespaces to the directory layout. ) *i$e Kr+ger !!, - 3 +ndent"tion 3.1 %ra&&ing 0ines .hen an expression will not fit on a single line, brea$ it up according to these general principles/ 0rea$ after a comma. 0rea$ after an operator. %refer higher1level brea$s to lower1level brea$s. 2lign the new line with the beginning of the expression at the same level on the previous line 3xample of brea$ing up method calls/ longMethodCall(expr1, expr2, expr3, expr, expr!"# 3xamples of brea$ing an arithmetic expression/ %43(34/ $ar % a & ' / (c ( g ) *" ) & +# 025 6T7"3 8 29#I5/ $ar % a & ' / (c ( g ) *" ) & +# The first is preferred, since the brea$ occurs outside the paranthesi:ed expression &higher level rule'. ;ote that you indent with tabs to the indentation level and then with spaces to the brea$ing position in our example this would be/ , $ar % a & ' / (c ( g ) *" ) , ...... & +# .here '<' are tab chars and '.' are spaces. &the spaces after the tab char are the indent with of the tab'. 2 good coding practice is to ma$e the tab and space chars visible in the editor which is used. 3.2 %hite S&a"es 2n indentation standard using spaces never was achieved. 6ome people li$e spaces, some prefer = and others die for >, or even more spaces. 0etter use tabs. Tab characters have some advantages/ 3veryone can set their own preferred indentation level It is only - character and not , =, > ? therefore it will reduce typing &even with smartindenting you have to set the indentation manually sometimes, or ta$e it bac$ or whatever' If you want to increase the indentation &or decrease', mar$ one bloc$ and increase the indent level with Tab with 6hift1Tab you decrease the indentation. This is true for almost any texteditor. @ere, we define the Tab as the standard indentation character. Don't use spaces for indentation - use tabs! ) *i$e Kr+ger !!, , Coents 4.1 1lo"2 Comments 0loc$ comments should usually be avoided. (or descriptions use of the /// comments to give C standard descriptions is recommended. .hen you wish to use bloc$ comments you should use the following style / /& -ine 1 & -ine 2 & -ine 3 &/ 2s this will set off the bloc$ visually from code for the &human' reader. 2lternatively you might use this oldfashioned C style for single line comments, even though it is not recommended. In case you use this style, a line brea$ should follow the comment, as it is hard to see code preceeded by comments in the same line/ /& 'lah 'lah 'lah &/ 0loc$ comments may be useful in rare cases, refer to the Tech;ote 'The fine 2rt of Commenting' for an example. Aenerally bloc$ comments are useful for comment out large sections of code. 4.2 Single 0ine Comments 7ou should use the // comment style to Bcomment outB code &6harp5evelop has a $ey for it, 2ltC/' . It may be used for commenting sections of code too. 6ingle line comments must be indented to the indent level when they are used for code documentation. Commented out code should be commented out in the first line to enhance the visibility of commented out code. 2 rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code. 4.3 !o"umentation Comments In the .net framewor$, *icrosoft has introduced a documentation generation system based on D*" comments. These comments are formally single line C comments containing D*" tags. They follow this pattern for single line comments/ /// .su//ary, /// This class... /// ./su//ary, *ultiline D*" comments follow this pattern/ /// .exception cre*%01ogus2xception0, /// This exception gets thro3n as soon as a /// 1ogus *lag gets set. /// ./exception, 2ll lines must be preceded by three slashes to be accepted as D*" comment lines. Tags fall into two categories/ 5ocumentation items (ormatting/4eferencing The first category contains tags li$e .su//ary,, .para/, or .exception,. These represent items that represent the elements of a program's 2%I which must be documented for the program to be useful to ) *i$e Kr+ger !!, , other programmers. These tags usually have attributes such as na/e or cre* as demonstrated in the multiline example above. These attributes are chec$ed by the compiler, so they should be valid. The latter category governs the layout of the documentation, using tags such as .code,, .list, or .para,. 5ocumentation can then be generated using the 'documentation' item in the Edevelop 'build' menu. The documentation generated is in @T*"@elp format. (or a fuller explanation of D*" comments see the *icrosoft .net framewor$ 65K documentation. (or information on commenting best practice and further issues related to commenting, see the Tech;ote 'The fine 2rt of Commenting'. - .ecl"r"tions .1 (umber o/ !e"larations &er 0ine #ne declaration per line is recommended since it encourages commenting - . In other words, int le$el# // indentation le$el int si+e# // si+e o* ta'le 5o not put more than one variable or variables of different types on the same line when declaring them. 3xample/ int a, '# //4hat is 5a56 4hat does 5'5 stand *or6 The above example also demonstrates the drawbac$s of non1obvious variable names. 0e clear when naming variables. .2 Initialization Try to initiali:e local variables as soon as they are declared. (or example/ string na/e % /y7'ject.8a/e# or int $al % ti/e.9ours# ;ote/ If you initiali:e a dialog try to use the using statement/ using (7pen:ile;ialog open:ile;ialog % ne3 7pen:ile;ialog("" < ... = .3 Class and Inter/a"e !e"larations .hen coding C classes and interfaces, the following formatting rules should be followed/ ;o space between a method name and the parenthesis B(B starting its parameter list. The opening brace B<B appears in the next line after the declaration statement. The closing brace B =B starts a line by itself indented to match its corresponding opening brace. (or example / class MySa/ple > MyClass, ?My?nter*ace < int /y?nt# - #f course, using self1explanatory variable names such as indent-e$el ma$e these comments obsolete. ) *i$e Kr+ger !!, =
$oid 2/ptyMethod(" < = = (or a brace placement example loo$ at section -!.-. / St"teents #.1 Sim&le Statements 3ach line should contain only one statement. #.2 3eturn Statements 2 return statement should not use outer most parentheses. 5on't use / return (n & (n ) 1" / 2"# use / return n & (n ) 1" / 2# #.3 I/4 i/5else4 i/ else5i/ else Statements i*, i*(else and i* else(i* else statements should loo$ li$e this/ i* (condition" < ;oSo/ething("# ... = i* (condition" < ;oSo/ething("# ... = else < ;oSo/ething7ther("# ... = i* (condition" < ;oSo/ething("# ... = else i* (condition" < ;oSo/ething7ther("# ... = else < ;oSo/ething7ther@gain("# ... = ) *i$e Kr+ger !!, F #.4 For 6 Forea"h Statements 2 *or statement shoud have following form / *or (int i % A# i . !# ))i" < ... = or single lined &consider using a while statement instead' / *or (initiali+ation# condition# update" # 2 *oreach should loo$ li$e / *oreach (int i in ?nt-ist" < ... = ;ote/ Aenerally use brac$ets even if there is only one statement in the loop. #. %hile6do57hile Statements 2 3hile statement should be written as follows/ 3hile (condition" < ... = 2n empty 3hile should have the following form/ 3hile (condition" # 2 do(3hile statement should have the following form/ do < ... = 3hile (condition"# #.# S7it"h Statements 2 s3itch statement should be of following form/ s3itch (condition" < case @> ... 'reaB# case 1> ... 'reaB# de*ault> ... 'reaB# = #.$ 8ry5"at"h Statements 2 try(catch statement should follow this form/ ) *i$e Kr+ger !!, G try < ... = catch (2xception" <= or try < ... = catch (2xception e" < ... = or try < ... = catch (2xception e" < ... = *inally < ... = 0 1hite S#"ce $.1 1lan2 0ines 0lan$ lines improve readability. They set off bloc$s of code which are in themselves logically related. Two blan$ lines should always be used between/ "ogical sections of a source file Class and interface definitions &try one class/interface per file to prevent this case' #ne blan$ line should always be used between/ *ethods %roperties "ocal variables in a method and its first statement "ogical sections inside a method to improve readability ;ote that blan$ lines must be indented as they would contain a statement this ma$es insertion in these lines much easier. $.2 Inter5term s&a"ing There should be a single space after a comma or a semicolon, for example/
TestMethod(a, ', c"# don5t use > TestMethod(a,',c" or TestMethod( a, ', c "#
6ingle spaces surround operators &except unary operators li$e increment or logical not', example/ a % '# // don5t use a%'# *or (int i % A# i . 1A# ))i" // don5t use *or (int i%A# i.1A# ))i" // or // *or(int i%A#i.1A#))i" ) *i$e Kr+ger !!, H $.3 8able li2e /ormatting 2 logical bloc$ of lines should be formatted as a table/ string na/e % CMr. 2dC# int /yDalue % !# Test aTest % Test.TestEou# Ise spaces for the table li$e formatting and not tabs because the table formatting may loo$ strange in special tab intent levels. ) *i$e Kr+ger !!, > 2 3"ing Con4entions '.1 Ca&italization Styles 2.$.$ 5"sc"l C"sing This convention capitali:es the first character of each word &as in TestCounter'. 2.$.' C"el C"sing This convention capitali:es the first character of each word except the first one. 3.g. testCounter. 2.$.3 6##er c"se #nly use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use %ascal Casing instead. (or 3xample/ pu'lic class Math < pu'lic const P? % ... pu'lic const 2 % ... pu'lic const *eigen1au/8u/'er % ... = '.2. (aming Guidelines Aenerally the use of underscore characters inside names and naming according to the guidelines for @ungarian notation are considered bad practice. @ungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. This style of naming was widely used in early .indows programming, but now is obsolete or at least should be considered deprecated. Ising @ungarian notation is not allowed if you follow this guide. 2nd remember/ a good variable name describes the semantic not the type. 2n exception to this rule is AII code. 2ll fields and variable names that contain AII elements li$e button should be postfixed with their type name without abbreviations. (or example/ Syste/.4indo3s.:or/s.1utton cancel1utton# Syste/.4indo3s.:or/s.Text1ox na/eText1ox# 2.'.$ Cl"ss 3"ing Guidelines Class names must be nouns or noun phrases. Ise%ascal Casing see >.-.- 5o not use any class prefix 2.'.' +nter7"ce 3"ing Guidelines ;ame interfaces with nouns or noun phrases or adJectives describing behavior. &3xample ?Co/ponent or ?2nu/'era'le' Ise %ascal Casing &see >.-.-' Ise I as prefix for the name, it is followed by a capital letter &first char of the interface name' 2.'.3 8nu 3"ing Guidelines Ise %ascal Casing for enum value names and enum type names 5onKt prefix &or suffix' a enum type or enum values Ise singular names for enums Ise plural name for bit fields. ) *i$e Kr+ger !!, L 2.'., 9e"d)nly "nd Const (ield 3"es ;ame static fields with nouns, noun phrases or abbreviations for nouns Ise %ascal Casing &see >.-.-' 2.'.- 5"r"eter:non const 7ield 3"es 5o use descriptive names, which should be enough to determine the variable meaning and itKs type. 0ut prefer a name thatKs based on the parameterKs meaning. Ise Camel Casing &see >.-.' 2.'./ V"ri"ble 3"es Counting variables are preferably called i, j, B, l, /, n when used in 'trivial' counting loops. &see -!. for an example on more intelligent naming for global counters etc.' Ise Camel Casing &see >.-.' 2.'.0 Method 3"es ;ame methods with verbs or verb phrases. Ise %ascal Casing &see >.-.' 2.'.2 5ro#erty 3"es ;ame properties using nouns or noun phrases Ise %ascal Casing &see >.-.' Consider naming a property with the same name as itKs type 2.'.; 84ent 3"es ;ame event handlers with the 2$ent9andler suffix. Ise two parameters named sender and e Ise %ascal Casing &see >.-.-' ;ame event argument classes with the 2$ent@rgs suffix. ;ame event names that have a concept of pre and post using the present and past tense. Consider naming events using a verb. 2.'.$0 C"#it"li*"tion su"ry Type Case Notes Class / 6truct %ascal Casing Interface %ascal Casing 6tarts with ? 3num values %ascal Casing 3num type %ascal Casing 3vents %ascal Casing 3xception class %ascal Casing 3nd with 2xception public (ields %ascal Casing *ethods %ascal Casing ;amespace %ascal Casing %roperty %ascal Casing %rotected/private (ields Camel Casing %arameters Camel Casing ) *i$e Kr+ger !!, -! ; 5rogr"ing 5r"ctices *.1 9isibility 5o not ma$e any instance or class variable pu'lic, ma$e them pri$ate. (or private members prefer not using Fpri$ate0 as modifier Just do write nothing. %rivate is the default case and every C programmer should be aware of it. Ise properties instead. 7ou may use pu'lic static fields &or const" as an exception to this rule, but it should not be the rule. *.2 (o :magi": (umbers 5onKt use magic numbers, i.e. place constant numerical values directly into the source code. 4eplacing these later on in case of changes &say, your application can now handle ,F=! users instead of the =H hardcoded into your code in F! lines scattered troughout your F!!! "#C' is error1prone and unproductive. Instead declare a const variable which contains the number / pu'lic class MyMath < pu'lic const dou'le P? % 3.11!G... = ) *i$e Kr+ger !!, -- $0 Code 8<"#les 1,.1 1ra"e &la"ement e.am&le na/espace Sho3MeThe1racBet < pu'lic enu/ Test < TestMe, TestEou =
pu'lic class TestMeClass < Test test#
pu'lic Test Test < get < return test# = set < test % $alue# = =
$oid ;oSo/ething(" < i* (test %% Test.TestMe" < //...stu** gets done = else < //...other stu** gets done = = = = 0rac$ets should begin on a new line only after/ ;amespace declarations ¬e that this is new in version !., and was different in !.' Class/Interface/6truct declarations *ethod declarations ) *i$e Kr+ger !!, - 1,.2 9ariable naming e.am&le instead of / *or (int i % 1# i . nu/# ))i" < /eetsCriteriaHiI % true# = *or (int i % 2# i . nu/ / 2# ))i" < int j % i ) i# 3hile (j .% nu/" < /eetsCriteriaHjI % *alse# j )% i# = = *or (int i % A# i . nu/# ))i" < i* (/eetsCriteriaHiI" < Console.4rite-ine(i ) C /eets criteriaC"# = = try intelligent naming / *or (int pri/eCandidate % 1# pri/eCandidate . nu/# ))pri/eCandidate" < isPri/eHpri/eCandidateI % true# = *or (int *actor % 2# *actor . nu/ / 2# ))*actor" < int *actora'le8u/'er % *actor ) *actor# 3hile (*actora'le8u/'er .% nu/" < isPri/eH*actora'le8u/'erI % *alse# *actora'le8u/'er )% *actor# = = *or (int pri/eCandidate % A# pri/eCandidate . nu/# ))pri/eCandidate" < i* (isPri/eHpri/eCandidateI" < Console.4rite-ine(pri/eCandidate ) C is pri/e.C"# = = Note: Indexer variables generally should be called i, j, B etc. 0ut in cases li$e this, it may ma$e sense to reconsider this rule. In general, when the same counters or indexers are reused, give them meaningful names. ) *i$e Kr+ger !!, -,