Coding Standards for C#



Similar documents
Transition your MCPD Web Developer Skills to MCPD ASP.NET Developer 3.5 (VB)

C # Coding Standards for.net By Lance Hunt. Document Version 1.15 March Copyright Lance Hunt 2007 All Rights Reserved

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

C Coding Style Guide. Technotes, HowTo Series. 1 About the C# Coding Style Guide. 2 File Organization. Version 0.3. Contents

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Sample Chapters. To learn more about this book visit Microsoft Learning at:

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Pemrograman Dasar. Basic Elements Of Java

Install Java Development Kit (JDK) 1.8

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

CS 106 Introduction to Computer Science I

Expanded contents. Section 1. Chapter 2. The essence off ASP.NET web programming. An introduction to ASP.NET web programming

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

2. Modify default.aspx and about.aspx. Add some information about the web site.

MCTS:.NET Framework 4, Web Applications

Yarmouk University Faculty of Science and Information Technology Department of Computer Information Systems CIS 282 Developing Web Applications

Example of a Java program

National Database System (NDS-32) Macro Programming Standards For Microsoft Word Annex - 8

JavaScript: Control Statements I

Introduction to Visual Studio and C#

Stacks. Linear data structures

Getting Started with the Internet Communications Engine

SQL Server Database Web Applications

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

C++ INTERVIEW QUESTIONS

Lecture 2 Notes: Flow of Control

Taxi Service Coding Policy. Version 1.2

Java Application Developer Certificate Program Competencies

CS 111 Classes I 1. Software Organization View to this point:

Code convention document Argus-viewer

CSE 308. Coding Conventions. Reference

PL / SQL Basics. Chapter 3

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Working with Data in ASP.NET 2.0 :: Paging and Sorting Report Data Introduction. Step 1: Adding the Paging and Sorting Tutorial Web Pages

Moving from CS 61A Scheme to CS 61B Java

Computer Programming I & II*

Conditions & Boolean Expressions

Introduction to Python

Java Interview Questions and Answers

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

C++ Language Tutorial

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

A Step by Step Guide for Building an Ozeki VoIP SIP Softphone

VB.NET Programming Fundamentals

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Software Development (CS2500)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Basic Programming and PC Skills: Basic Programming and PC Skills:

Semantic Analysis: Types and Type Checking

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

ECE 122. Engineering Problem Solving with Java

Java Basics: Data Types, Variables, and Loops

Software Engineering Techniques

ASP.NET Dynamic Data

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Applied Informatics C++ Coding Style Guide

Course Title: Software Development

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Java

Introduction to Java. CS 3: Computer Programming in Java

Object Oriented Software Design

UML for C# Modeling Basics

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Quosal Form Designer Training Documentation

CS 241 Data Organization Coding Standards

Fundamentals of Programming and Software Development Lesson Objectives

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

AP Computer Science Java Subset

Fundamentals of Java Programming

Lecture 5: Java Fundamentals III

TIP: To access the WinRunner help system at any time, press the F1 key.

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

CS106A, Stanford Handout #38. Strings and Chars

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Sources: On the Web: Slides will be available on:

Chapter 1 Java Program Design and Development

Some Scanner Class Methods

Version ENCORE SYSTEMS LLC. Web Development and ecommerce Integration. PayPal SOAP API Class Library User Guide

Computer Programming I

Ecma/TC39/2013/NN. 4 th Draft ECMA-XXX. 1 st Edition / July The JSON Data Interchange Format. Reference number ECMA-123:2009

Exercise 4 Learning Python language fundamentals

MISRA-C:2012 Standards Model Summary for C / C++

13 Classes & Objects with Constructors/Destructors

Programming Languages CIS 443

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Contents. 9-1 Copyright (c) N. Afshartous

An Incomplete C++ Primer. University of Wyoming MA 5310

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

LabVIEW Day 6: Saving Files and Making Sub vis

Transcription:

DotNetDaily.net Coding Standards for C# 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.

1 Coding Standards for C# Contents 1. Naming Conventions... 2 1.1 General Rules... 2 1.2 Naming Conventions for ASP.NET Controls... 3 2. Indentation, Spacing and Coding Style... 5 2.1 General Rules... 5 2.2 Grouping Code... 6 3. Language Usage... 7 3.1 General Rules... 7 4. Code Commenting... 9 4.1 General Rules... 9 5. Exception Handling... 10 5.1 General Rules... 10

2 Coding Standards for C# C# Coding Standards for.net 1. Naming Conventions Terminology and Definitions: Camel Case (camelcase): The first letter of the word is lower case and then each first letter of the part of the word is upper case; Pascal Case (PascalCase): The first letter of the word is upper case and then each first letter of the part of the word is upper case; Underscode Prefix (_underscore): The word begins with underscore char and for the rest of the word use camelcase rule; 1.1 General Rules 1.1.1 Use Pascal Case for Class names: public class HelloWorld... ; 1.1.2 Use Pascal Case for Method names: public void SayHello(string name)... ; 1.1.3 Use Camel Case for variables and method parameters: int totalcount = 0; void SayHello(string name) string fullmessage = "Hello " + name;... 1.1.4 Avoid all upper case or all lower case names; 1.1.5 Do not use Hungarian notation: Example of Hungarian Notation: string m_sname; (the prefix m_ means that is a member variable and s means that is a string data type);

3 Coding Standards for C# 1.1.6 Avoid abbreviations longer than 5 characters; 1.1.7 Avoid using abbreviations unless the full name is excessive: 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: 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: 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. protected void SaveCustomerName(string customername) //code here... 1.2 Naming Conventions for ASP.NET Controls In general, naming ASP.NET controls is made using Camel Case naming convention, where the prefix of the name is the abbreviation of the control type name.

4 Coding Standards for C# Abbreviation ASP.NET Control STANDARD CONTROLS btn Button cb CheckBox cbl CheckBoxList ddl DropDownList fu FileUpload hdn HiddenField lnk Hyperlink img Image ibtn(btn) ImageButton lbl Label lbtn(btn) LinkButton lb ListBox lit Literal mv MultiView pnl Panel ph PlaceHolder rb RadioButton rbl RadioButtonList tbl Table txt TextBox v View DATA CONTROLS dtl DataList dp DataPager dtv DetailsView ets EntityDataSource fv FormView gv GridView lds LinqDataSource lv ListView ods ObjectDataSource qe QueryExtender rpt Repeater smd SiteMapDataSource sds SqlDataSource xds XmlDataSource VALIDATION CONTROLS cpv CompareValidator ctv CustomValidator rv RangeValidator rev RegularExpressionValidator rfv RequiredFieldValidator vs ValidationSummary

5 Coding Standards for C# 2. Indentation, Spacing and Coding Style Each programmer has a unique way of coding. While this fact is not a problem when you do it for yourself, working in an organization and code in your own way may represent a big problem for your team mates. So it s very important to follow some indentation and coding style rules for keeping the code clean and readable for all programmers from the project. 2.1 General Rules 2.1.1 Use TAB for indentation. Do not use spaces. Recommended TAB size is 4; 2.1.2 Never declare more than one namespace per file; 2.1.3 Avoid putting multiple classes in a single file; 2.1.4 Comments should be in the same level as the code: // Format a message and display string fullmessage = "Hello " + name; DateTime currenttime = DateTime.Now; 2.1.5 Always use curly braces ( and ) in a new line and in conditional statements: 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: public void SayHello(string name) string fullmessage = "Hello " + name; DateTime currenttime = DateTime.Now; string message = fullmessage + ", the time is : " + currenttim e.toshorttimestring();

6 Coding Standards for C# MessageBox.Show(message); 2.2 Grouping Code 2.2.1 Group internal class implementation by type in the following order: 1) Member variables; 2) Constructors and finalizers; 3) Nested Enums, Structs and Classes; 4) Properties; 5) Methods; 2.2.2 Sequence declarations within type groups based upon access modifier and visibility: 1) Public; 2) Protected; 3) Internal; 4) Private; 2.2.3 Use regions (#region) to group related pieces of code together: namespace SampleApplication public partial class _Default : System.Web.UI.Page #region Private Members #region Constructors #region Public Properties #region Private Properties #region Public Methods #region Private Methods

7 Coding Standards for C# 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 it s a good candidate for refactoring. Split it logically in two or more classes; 3. Language Usage In.NET, if you don t 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. 3.1 General Rules 3.1.1 Do not omit access modifiers. Explicitly declare all identifiers with the appropriate access modifier instead of allowing them by default: Good: protected void SaveCustomerName(string customername) //... 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: if (name.tolower() == "john")

8 Coding Standards for C# // do something... 3.1.4 Use String.Empty instead of : Good: if (name == String.Empty) // 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: int result = isvalid? 9 : 4; 3.1.12 Avoid evaluating Boolean conditions against true or false: Good: if (!isvalid) //do something

9 Coding Standards for C# 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 General Rules 4.1.1 All comments should be written in the same language, be grammatically correct and contain appropriate punctuation; 4.1.2 Use // or /// but not /* */; 4.1.3 Do not use flower box comments //*************************** // flower box //*************************** 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:

10 Coding Standards for C# /// <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. 5.1 General Rules 5.1.1 Only catch exceptions that you can handle; 5.1.2 Avoid nesting try/catch within catch block; 5.1.3 Use finally block only for releasing used resources; 5.1.4 Always use validation to prevent the exception: Good: if (status!=null && status.iscompleted == true) //some code here 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;