0% found this document useful (0 votes)
169 views

Sharp Develop Coding Style

This document provides guidelines for C# coding style, including recommendations for file organization, indentation, comments, declarations, statements, and white space. Key points covered include using tabs for indentation rather than spaces, commenting guidelines like using XML comments, limiting declarations to one per line, and formatting control structures like if/else statements.

Uploaded by

amresh kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views

Sharp Develop Coding Style

This document provides guidelines for C# coding style, including recommendations for file organization, indentation, comments, declarations, statements, and white space. Key points covered include using tabs for indentation rather than spaces, commenting guidelines like using XML comments, limiting declarations to one per line, and formatting control structures like if/else statements.

Uploaded by

amresh kumar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

C Coding Guide

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

1 About 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.

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.

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.

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.

3.2 %hite S&a"es


-n indentation standard using spaces never was achieved. 1ome people li$e spaces, some prefer 8 and others die for 9, or even more spaces. +etter use tabs. Tab characters have some advantages* .veryone can set their own preferred indentation level It is only : character and not , 8, 9 ; therefore it will reduce typing &even with smartindenting you have to set the indentation manually sometimes, or ta$e it bac$ or whatever' 1 If you want to increase the indentation &or decrease', mar$ one bloc$ and increase the indent level with Tab with 1hift,Tab you decrease the indentation. This is true for almost any texteditor.
1 1

<ere, we define the Tab as the standard indentation character.

Don't use spaces for indentation - use tabs!


4 Comments
4.1 2lo"3 Comments
+loc$ 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 * /* Line 1 * Line 2 * Line 3 */ -s this will set off the bloc$ visually from code for the &human' reader. -lternatively 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* /* blah blah blah */ +loc$ comments may be useful in rare cases, refer to the Tech6ote 'The fine -rt of Commenting' for an example. =enerally bloc$ comments are useful for comment out large sections of code.

4.2 Single 0ine Comments

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.

4.3 !o"umentation Comments


In the .net framewor$, @icrosoft has introduced a documentation generation system based on A@" comments. These comments are formally single line C comments containing A@" tags. They follow this pattern for single line comments* /// <summary> /// This class... /// </summary> @ultiline A@" comments follow this pattern* /// /// /// /// <exception cref=BogusException> This exception gets thrown as soon as a Bogus flag gets set. </exception>

-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.

.1 (umber o/ !e"larations &er 0ine

.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()) { ... }

.3 Class and Inter/a"e !e"larations


)hen coding C classes and interfaces, the following formatting rules should be followed* 6o space between a method name and the parenthesis >(> starting its parameter list. The opening brace >{> appears in the next line after the declaration statement. The closing brace > }> starts a line by itself indented to match its corresponding opening brace. (or example * class MySample : MyClass, IMyInterface { int myInt;
: #f course, using self,explanatory variable names such as indentLevel ma$e these comments obsolete.

C @i$e KrDger !!E


public MySample(int myInt) { this.myInt = myInt ; } void Inc() { ++myInt; } void EmptyMethod() { } } (or a brace placement example loo$ at section :!.:.

" Statements
#.1 Sim&le Statements
.ach line should contain only one statement.

#.2 4eturn Statements


- return statement should not use outer most parentheses. 0on't use * return (n * (n + 1) / 2); use * return n * (n + 1) / 2;

#.3 I/5 i/6else5 i/ else6i/ else Statements


if, if-else and if else-if else statements should loo$ li$e this* if (condition) { DoSomething(); ... } if (condition) { DoSomething(); ... } else { DoSomethingOther(); ... } if (condition) { DoSomething(); ... } else if (condition) { DoSomethingOther(); ... } else { DoSomethingOtherAgain(); ... }

#.4 For 7 Forea"h Statements


- for statement shoud have following form * for (int i = 0; i < 5; ++i) { ... } or single lined &consider using a while statement instead' * for (initialization; condition; update) ; - foreach should loo$ li$e * foreach (int i in IntList) { ... } 6ote* =enerally use brac$ets even if there is only one statement in the loop.

#. %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*

do { ... } while (condition);

#.# S8it"h Statements


- switch statement should be of following form* switch (condition) { case A: ... break; case B: ... break; default: ... break; }

#.$ 9ry6"at"h Statements


- try-catch statement should follow this form* try { ... } catch (Exception) {}

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'

#ne blan$ line should always be used between*


1 1 1

@ethods %roperties "ocal variables in a method and its first statement

"ogical sections inside a method to improve readability

6ote that blan$ lines must be indented as they would contain a statement this ma$es insertion in these lines much easier.

$.2 Inter6term s&a"ing


There should be a single space after a comma or a semicolon, for example* TestMethod(a, b, c); don't use : TestMethod(a,b,c) or TestMethod( a, b, c );

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 9able li3e /ormatting


- logical bloc$ of lines should be formatted as a table* string name = "Mr. Ed"; int myValue = 5; Test aTest = Test.TestYou; Fse spaces for the table li$e formatting and not tabs because the table formatting may loo$ strange in special tab intent levels.

& 'aming Con(entions


The original of this document was developed by the @icrosoft special interest group. )e made some addons. This document explains the naming conventions that should be used with .6.T proGects. - consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library. )idespread use and understanding of these naming guidelines should eliminate unclear code and ma$e it easier for developers to understand shared code.

'.1 Ca&italization Styles !e/ined


)e define three types of capitali5ation styles* Pascal case The first letter in the identifier and the first letter of each subseHuent concatenated word are capitali5ed. .xample* BackColor, DataSet Camel case The first letter of an identifier is lowercase and the first letter of each subseHuent concatenated word is capitali5ed. .xample* numberOfDays, isValid Uppercase

-ll letters in the identifier are capitali5ed. .xample* D, P

'.2 :ungarian 9y&e (otation !e/ined


<ungarian notation is any of a variety of standards for organi5ing a computer program by selecting a schema for naming your variables so that their type is readily available to someone familiar with the notation. It is in fact a commenting techniHue. .xample* str!irst"ame, i"umberOfDays There are different opinions about using this $ind of type notation in programming nowadays. 1ome say that itIs useful, and it should be used everywhere to enhance clarity of your code. #thers say it Gust obfuscates your code, because it has no real advantage in modern programming environments. #ur point of view is a moderated one* use it wisely, meaning, we only use <ungarian notation for pri#ate or local #ariables, that are only accessible and interesting to the programmer of the class. Don$t use it %it& public variables, properties or parameters in methods, because they are exposed to the outside world. 1omeone who uses your classes and accesses properties of your class, is not interested in type, but Gust wants to use them. In the .6.T framewor$, there are a lot of types, so we extended and adapted the <ungarian notation with our own type notation.

'.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

'.3.2 0o"al ;ariables (aming Guidelines


"amin' 'uidelines %refix private or local variables with <ungarian,style notation.

Case 'uidelines Fse camel case as a general rule, or uppercase for very small words .xample* str!irst"ame, dset)mployees

'.3.3 (ames&a"e (aming Guidelines


"amin' 'uidelines The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows* Company"ame*+ec&nolo'y"ame,*!eature-,*Desi'n%refixing namespace names with a company name or other well,established brand avoids the possibility of two published namespaces having the same name. Fse a stable, recogni5ed technology name at the second level of a hierarchical name. .xample* .kadia*+raffic, System*/eb*U , System*/indo%s*!orms Case 'uidelines Fse %ascal case as a general rule, or uppercase for very small words. .xample* System*/indo%s*!orms, System*/eb*U

'.3.4 Class (aming Guidelines


"amin' 'uidelines Fse a noun or noun phrase to name a class. 0o not use a type prefix, such as C for class, on a class name. 0o not use the underscore character &J'. Case 'uidelines Fse %ascal case. .xample* !ileStream, Button

'.3. Inter/a"e (aming Guidelines


"amin' 'uidelines %refix interface names with the letter >I>, to indicate that the type is an interface. 0o not use the underscore character &J'. Case 'uidelines Fse %ascal case. .xample* Ser#icePro#ider, !ormatable

'.3.# +arameter (aming Guidelines

"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

'.3.$ >ethod (aming Guidelines


"amin' 'uidelines Fse verbs or verb phrases to name methods. Case 'uidelines Fse %ascal case. .xample* 1emo#e.ll23, 4etC&ar.t23

'.3.' +ro&erty 7 -numerations (aming Guidelines


"amin' 'uidelines Fse a noun or noun phrase to name properties. 0o not use <ungarian notation. Case 'uidelines Fse %ascal case. .xample* BackColor, "umberOf tems

'.3.* -)ent (aming Guidelines


"amin' 'uidelines Fse an .vent<andler suffix on event handler names. 1pecify two parameters named sender and e. The sender parameter represents the obGect that raised the event. The sender parameter is always of type obGect, even if it is possible to use a more specific type. The state associated with the event is encapsulated in an instance of an event class named 0e0. Fse an appropriate and specific event class for the e parameter type. 6ame an event argument class with the )#ent.r's suffix. Case 'uidelines Fse %ascal case. .xample* public dele'ate #oid 5ouse)#ent6andler2ob7ect sender, 5ouse)#ent.r's e38

'.3.1, -."e&tion (aming Guidelines

"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

'.3.11 Constant (aming Guidelines


The names of variables declared class constants should be all uppercase with words separated by underscores. It is recommended to use a grouping naming schema. .xample &for group -%J)I6'* .P(/ "(5 "(/ D+6, .P(/ "(5.:(/ D+6, .P(/ "(5 "(6 46+, .P(/ "(5.:(6 46+

'.3.12 C# +rimiti)e 9y&e (otation


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

'.3.13 ;isual Control 9y&e (otation


-ssembly +oolean +utton Char Chec$+ox Combo+ox Container 0ataColumn 0ata=rid 0ata=rid0ateTime%ic$erColumn 0ata=ridTable1tyle 0ata=ridText+oxColumn 0ata/eader 0ata/ow 0ata1et 0ataTable 0ateTime 0ialog 0ialog/esult 0ouble .xception asm bln btn ch cbx cmb ctr dcol dgrid dgdtpc dgts dgtbc dreader drow dset dtable date dialog dr dbl ex

=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.

*.2 (o ?magi"? (umbers


0onIt use magic numbers, i.e. place constant numerical values directly into the source code. /eplacing these later on in case of changes &say, your application can now handle EO8! users instead of the 8 P hardcoded into your code in O! lines scattered troughout your O!!! "#C' is error,prone and unproductive. Instead declare a const variable which contains the number * public class MyMath { public const double PI = 3.14159... }

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 &note that this is new in version !.E and was different in !. ' Class/Interface/1truct declarations @ethod declarations

1,.2 ;ariable naming e.am&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 naming * 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; 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.

You might also like