Sharp Develop Coding Style
Sharp Develop Coding Style
Contents
Style
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
2 File Organization
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.
3 Indentation
3.1 %ra&&ing 0ines
)hen an expression will not fit on a single line, brea$ it up according to these general principles* 1 1 1 1 +rea$ after a comma. +rea$ after an operator. %refer higher,level brea$s to lower,level brea$s. -lign the new line with the beginning of the expression at the same level on the previous line
.xample of brea$ing up method calls* longMethodCall(expr1, expr2, expr3, expr4, expr5); .xamples of brea$ing an arithmetic
expression* %/.(./* var = a * b / (c - g + f) + 4 * z; +-0 1T2". 3 -4#I0* var = a * b / (c - g + f) + 4 * z; The first is preferred, since the brea$ occurs outside the paranthesi5ed expression &higher level rule'. 6ote that you indent with tabs to the indentation level and then with spaces to the brea$ing position in our example this would be* > > var = a * b / (c - g + f) + ......4 * z;
)here '7' are tab chars and '.' are spaces. &the spaces after the tab char are the indent with of the tab'. - good coding practice is to ma$e the tab and space chars visible in the editor which is used.
2ou should use the // comment style to >comment out> code &1harp0evelop has a $ey for it, -lt?/' . It may be used for commenting sections of code too. 1ingle 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. - 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.
-ll lines must be preceded by three slashes to be accepted as A@" comment lines. Tags fall into two categories* 0ocumentation items (ormatting//eferencing The first category contains tags li$e <summary>, <param> or <exception>. These represent items that represent the elements of a program's -%I which must be documented for the program to be useful to other programmers. These tags usually have attributes such as name or cref 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>.
0ocumentation can then be generated using the 'documentation' item in the Bdevelop 'build' menu. The documentation generated is in <T@"<elp format. (or a fuller explanation of A@" comments see the @icrosoft .net framewor$ 10K documentation. (or information on commenting best practice and further issues related to commenting, see the Tech6ote 'The fine -rt of Commenting'.
5 e!larations
#ne declaration per line is recommended since it encourages commenting:. In other words, int level; // indentation level int size; // size of table 0o not put more than one variable or variables of different types on the same line when declaring them. .xample* int a, b; //What is 'a'? What does 'b' stand for? The above example also demonstrates the drawbac$s of non,obvious variable names. +e clear when naming variables.
.2 Initialization
Try to initiali5e local variables as soon as they are declared. (or example* string name = myObject.Name;
or
int val = time.Hours;
6ote* If you initiali5e a dialog try to use the using statement* using (OpenFileDialog openFileDialog = new OpenFileDialog()) { ... }
" Statements
#.1 Sim&le Statements
.ach line should contain only one statement.
#. %hile7do68hile Statements
- while statement should be written as follows* while (condition) { ... } -n empty while should have the following form* while (condition) ; - do-while statement should have the following form*
or
try { ... } catch (Exception e) { ... } or try { ... } catch (Exception e) { ... } finally { ... }
# $hite S%a!e
$.1 2lan3 0ines
+lan$ lines improve readability. They set off bloc$s of code which are in themselves logically related. Two blan$ lines should always be used between*
1 1
"ogical sections of a source file Class and interface definitions &try one class/interface per file to prevent this case'
6ote that blan$ lines must be indented as they would contain a statement this ma$es insertion in these lines much easier.
1ingle spaces surround operators &except unary operators li$e increment or logical not', example* 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)
'.3 (aming Guidelines '.3.1 +ri)ate ;ariables <Fields in C#= (aming Guidelines
"amin' 'uidelines %refix private variables with a >J> and <ungarian,style notation. Case 'uidelines Fse camel case as a general rule, or uppercase for very small words .xample* (str!irst"ame, (dset)mployees // (ield private #le0bConnection (connectionK // %roperty public #le0bConnection Connection L get L return (connectionK M set L (connection N valueK M M
Case 'uidelines Fse camel case as a general rule, or uppercase for very small words .xample* str!irst"ame, dset)mployees
"amin' 'uidelines Fse descriptive parameter names. %arameter names should be descriptive enough that the name of the parameter and its type can be used to determine its meaning in most scenarios. To distinguish parameters from other variables the prefix 0p0 should be used. 0o not prefix parameter names with <ungarian type notation. 0o not use a prefix for parameter names of an event handler and exceptions. Case 'uidelines Fse camel case. .xample* p+ype"ame, p"umberOf tems
"amin' 'uidelines .vent handlers in 4isual 1tudio .6.T tend to use an >e> parameter for the event parameter to the call. To ensure we avoid a conflict, we will use >e9> as a standard variable name for an .xception obGect. .xample catch &.xception e9' L // <andle .xception M
=roup+ox <ashTable Image"ist Integer "abel "ist+ox "ist4iew @arshall+y/ef#bGect @ainmenu @enuItem @0I,(rame @0I,1heet 6umericFp0own %anel %icture+ox /adio+utton 10I,(orm 1HlCommand 1HlCommand+uilder 1HlConnection 1Hl0ata-dapter 1tatus+ar 1tring 1tring+uilder TabControl Tab%age Text+ox Tool+ar Tool+ar+utton Timer FserControl )indows%rincipal
gbx htbl iml int lbl lbx lv rmt mm mi frame sheet nud pnl pbx rbtn form sHlcom sHlcomb sHlcon sHlda stb str strb tabctrl tabpage tbx tbr tbb tmr usr wpl
) *rogramming *ra!ti!es
*.1 ;isibility
0o not ma$e any instance or class variable public, ma$e them private. (or private members prefer not using private as modifier Gust do write nothing. %rivate is the default case and every C programmer should be aware of it. Fse properties instead. 2ou may use public static fields &or const) as an exception to this rule, but it should not be the rule.
1+ Code ,-am%les
1,.1 2ra"e &la"ement e.am&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 new line only after* 6amespace declarations ¬e that this is new in version !.E and was different in !. ' Class/Interface/1truct declarations @ethod declarations
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; Indexer variables generally should be called i,j,k etc. +ut 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.