Professional Documents
Culture Documents
Coding Standards Csharp
Coding Standards Csharp
net
This document was downloaded from http://www.dotnetdaily.net/ You are permitted to use and distribute this document for any noncommercial purpose as long as you retain this license & copyrights information. This document is provided on As-Is basis. The author of this document will not be responsible for any kind of loss for you due to any inaccurate information provided in this document.
Contents
1. Naming Conventions ....................................................................................................................... 2 1.1 1.2 2. General Rules........................................................................................................................... 2 Naming Conventions for ASP.NET Controls............................................................................. 3
Indentation, Spacing and Coding Style ............................................................................................ 5 2.1 2.2 General Rules........................................................................................................................... 5 Grouping Code......................................................................................................................... 6
3.
4.
5.
http://dotnetdaily.net
http://dotnetdaily.net
1.1.6 Avoid abbreviations longer than 5 characters; 1.1.7 Avoid using abbreviations unless the full name is excessive: Ex: Good: string address; Not good: string addr;
1.1.8 Use meaningfull, descriptive words for naming variables; 1.1.9 Try to prefix Boolean variables with Can, Is or Has; 1.1.10 Do not use Underscore Prefix for local variables names; 1.1.11 All member variables must use Underscore Prefix so that they can be identified from other local variables names; 1.1.12 Avoid naming conflicts with existing .NET Framework namespaces or types; 1.1.13 Do not include the parent class name within a property name: Ex: Good: Customer.Name; Not good: Customer.CustomerName;
1.1.14 When defining a root namespace, use a Product, a Company or a Developer name as the root: Ex: NorthwindApplication.Utilities; 1.1.15 Use Pascal Case for file names; 1.1.16 Method name should tell you what it does; 1.1.17 A method should do only one job. Do not combine multiple jobs in one method even if those jobs have very few lines of code. Ex:
protected void SaveCustomerName(string customerName) { //code here... }
http://dotnetdaily.net
Abbreviation ASP.NET Control STANDARD CONTROLS Button btn CheckBox cb CheckBoxList cbl DropDownList ddl FileUpload fu HiddenField hdn Hyperlink lnk Image img ImageButton ibtn(btn) Label lbl LinkButton lbtn(btn) ListBox lb Literal lit MultiView mv Panel pnl PlaceHolder ph RadioButton rb RadioButtonList rbl Table tbl TextBox txt View v DATA CONTROLS DataList dtl DataPager dp DetailsView dtv EntityDataSource ets FormView fv GridView gv LinqDataSource lds ListView lv ObjectDataSource ods QueryExtender qe Repeater rpt SiteMapDataSource smd SqlDataSource sds XmlDataSource xds VALIDATION CONTROLS CompareValidator cpv CustomValidator ctv RangeValidator rv RegularExpressionValidator rev RequiredFieldValidator rfv ValidationSummary vs
http://dotnetdaily.net
2.1.5 Always use curly braces ({ and }) in a new line and in conditional statements: Ex:
protected void Page_Load(object sender, EventArgs e) { bool IsTrue; if (IsTrue == true) { // Do something; //.... return false; } }
2.1.6 Use one blank line to separate logical groups of code: Ex:
public void SayHello(string name) { string fullMessage = "Hello " + name; DateTime currentTime = DateTime.Now; string message = fullMessage + ", the time is : " + currentTim e.ToShortTimeString();
http://dotnetdaily.net
MessageBox.Show(message); }
http://dotnetdaily.net
2.2.4 Do not hardcode numbers and strings. Use constant variables or resource files; 2.2.5 Declare readonly or static readonly variables instead of constants for complex types; 2.2.6 Avoid having very large files. If a file has more than 1000 lines of code then its a good candidate for refactoring. Split it logically in two or more classes;
3. Language Usage
In .NET, if you dont respect some basic rules about language usage you can end up by spending a lot of time on debugging code and trace bugs caused by inadvertently written code.
Bad:
void SaveCustomerName(string customerName) { //... }
3.1.2 Only declare member variables as private. Use properties to provide access to them with public, protected or internal access modifiers; 3.1.3 Convert strings to lower case or upper case before comparing. This will ensure the string will match even if the string compared has a different case: Ex:
if (name.ToLower() == "john")
http://dotnetdaily.net
{ // do something... }
Bad:
if (name == "") { // do something... }
3.1.5 Try to use int for any non-fractional numeric values that will fit into int data type, even for negative numeric values; 3.1.6 Only use long for variables potentially containing values too large for int data type; 3.1.7 Use double for fractional numbers to insure decimal precisions in calcultations; 3.1.8 Use float for fractional number that will not fit in decimal or double. Still avoid using float unless you fully understand the implications upon any calculations; 3.1.9 Use String.Builder instead of string when you have to manipulate string objects in a loop; 3.1.10 Try to use @ prefix for string literals instead of escaped strings; 3.1.11 Avoid using ternary conditional operator. For complex operations can be difficult to understand: Ex:
int result = isValid ? 9 : 4;
3.1.12 Avoid evaluating Boolean conditions against true or false: Ex: Good:
if (!isValid) { //do something
http://dotnetdaily.net
Bad:
if (isValid == false) { //do something }
3.1.13 Use switch/case statements for simple operations with parallel conditional logic; 3.1.14 Prefer nested if/else over switch/case for short conditional sequences and complex conditions; 3.1.15 Prefer polymorphism over switch/case to encapsulate and delegate complex operations;
4. Code Commenting
Adding comments to your work is without doubt one of the most important factor in team working. More than that, it also represents the best technique for keeping the code maintainable in time. Have a look at rules below:
4.1.4 Use inline comments to explain assumptions, known issues and algorithm insights; 4.1.5 Do not use inline comments to explain obvious code. Well written code is self-documenting; 4.1.6 Always apply comment-blocks (///) to public, protected and internal declarations:
http://dotnetdaily.net
10
Ex:
/// <summary> /// Method used for saving customer's name /// </summary> /// <param name="name"></param> public void SaveCustomerName(string name)
5. Exception Handling
As programmers we always want to write code of the highest quality. Unfortunate we are not perfect so exceptions appear as a side effect of our code. Knowing that, we must not punish the user of our product to see our mistakes. Please take a look at the following basic rules about exception handling.
Bad:
if (status.IsCompleted == true) { //some code here }
5.1.5 Always add the [Serialize] attribute to exception classes; 5.1.6 Avoid re-throwing an exception; 5.1.7 Do not show important exception information to the client;
http://dotnetdaily.net