NAMING CONVENTIONS AND STANDARDS
Naming Conventions
Consistency is the key to maintainable code. This statement is most true for naming your projects, source files, and identifiers including Fields, Variables, Properties, Methods, Parameters, Classes, Interfaces, and Namespaces.
General Guidelines
- Always use Camel Case or Pascal Case names.
- Avoid ALL CAPS and all lowercase names. Single lowercase words or letters are acceptable.
- Do not create declarations of the same type (namespace, class, method, property, field, or parameter) and access modifier (protected, public, private, internal) that vary only by capitalization.
- Do not use names that begin with a numeric character.
- Do add numeric suffixes to identifier names.
- Always choose meaningful and specific names.
- Always err on the side of verbosity not terseness.
- Variables and Properties should describe an entity not the type or size.
- Do not use Hungarian Notation!
Example: strName or iCount
- Avoid using abbreviations unless the full name is excessive.
- Avoid abbreviations longer than 5 characters.
- Any Abbreviations must be widely known and accepted.
- Use uppercase for two-letter abbreviations, and Pascal Case for longer abbreviations.
- Do not use C# reserved words as names.
- Avoid naming conflicts with existing .NET Framework namespaces, or types.
- Avoid adding redundant or meaningless prefixes and suffixes to identifiers
Example:
// Bad!
public enum ColorsEnum {…} public class CVehicle {…}
public struct RectangleStruct {…}
- Do not include the parent class name within a property name.
Example: Customer.Name NOT Customer.CustomerName
- Try to prefix Boolean variables and properties with "Can", " Is" or " Has".
- Append computational qualifiers to variable names like Average, Count, Sum, Min, and Max where appropriate.
- When defining a root namespace, use a Product, Company, or Developer Name as the root.
Example:
LanceHunt.StringUtilities
NAME USAGE & SYNTAX
1. Identifier: Project File
Naming Convention: Pascal Case. Always match Assembly Name & Root Namespace.
Example: LanceHunt.Web.csproj -> LanceHunt.Web.dll ->
namespace LanceHunt.Web
2. Identifier: Source File
Naming Convention: Pascal Case. Always match Class name and file name. Avoid including more than one Class, Enum (global), or Delegate (global) per file. Use a descriptive file name when containing multiple Class, Enum, or Delegates.
Example: MyClass.cs=> public class MyClass{…}
3. Identifier: Resource or Embedded File
Naming Convention: Try to use Pascal Case. Use a name describing the file contents.
4. Identifier: Namespace
Naming Convention: Pascal Case. Try to partially match Project/Assembly Name.
Example: namespace LanceHunt.Web {…}
5. Identifier: Class or Struct
Naming Convention: Pascal Case. Use a noun or noun phrase for class name. Add an appropriate class-suffix when sub-classing another type when possible.
Examples:
private class MyClass {…}
internal class SpecializedAttribute : Attribute {…}
public class CustomerCollection : CollectionBase {…}
public class CustomEventArgs : EventArgs {…}
private struct ApplicationSettings {…}
6. Identifier: Interface
Naming Convention: Pascal Case. Always prefix interface name with capital "I".
Example: interface ICustomer{…}
7. Identifier: Generic Class & Generic Parameter Type [C#v2+]
Naming Convention:Always use a single capital letter, such as T or K.
Example:
public class FifoStack<T>
{
public void Push(<T> obj) {…}
public <T> Pop(){…}
}
8. Identifier: Method
Naming Convention: Pascal Case. Try to use a Verb or Verb-Object pair.
Example: public void Execute(){…}private string GetAssemblyVersion(Assembly target) {…}
9. Identifier: Property
Naming Convention
Pascal Case. Property name should represent the entity it returns. Never prefix property names with
"Get" or " Set".
Example:
public string Name
{
get{…} set{…} }
10. Identifier: Field(Public, Protected, or Internal)
Naming Convention: Pascal Case. Avoid using non-private Fields! Use Properties instead.
Example: public string Name;
protected IList InnerList;
11. Identifier: Field (Private)
Naming Convention: Camel Case and prefix with a single underscore (_) character.
Example: private string _name;
12. Identifier: Constant or Static Field
Naming Convention: Treat like a Field. Choose appropriate Field access-modifier above.
13. Identifier: Enum
Naming Convention:Pascal Case (both the Type and the Options). Add the FlagsAttribute to bit-mask multiple options.
Example:
public enum CustomerTypes
{ Consumer, Commercial}
14. Identifier: Delegate or Event
Naming Convention: Treat as a Field. Choose appropriate Field access-modifier above.
Example: public event EventHandler LoadPlugin;
15. Identifier: Variable (inline)
Naming Convention: Camel Case. Avoid enumerating variable names like text1, text2, text3 etc.
16. Identifier: Parameter
Naming Convention: Camel Case.
Example: public void Execute(string commandText, int iterations) {…}
Note : The terms Pascal Casing and Camel Casing are used throughout this Book. Pascal Casing - First character of all words are Upper Case and other characters are lower case. Example: BackColor Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case. Example: backColor |
1.Use Pascal casing for Class names
public class HelloWorld
{
...
}
2. Use Pascal casing for Method names
void SayHello(string name)
{
...
}
3. Use Camel casing for variables and method parameters
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}
4. Use the prefix "I" with Camel Casing for interfaces ( Example: IEntity )
5. Do not use Hungarian notation to name variables.
In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:
string m_sName;
int nAge;
However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.
Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable. |
6. Use Meaningful, descriptive words to name variables. Do not use abbreviations.
Good:
string address
int salary
Not Good:
string nam
string addr
int sal
7. Do not use single character variable names like i, n, s etc. Use names like index, temp
One exception in this case would be variables used for iterations in loops:
for ( int i = 0; i < count; i++ )
{
...
}
If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.
8. Do not use underscores (_) for local variable names.
9. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.
10. Do not use variable names that resemble keywords.
11. Prefix boolean variables, properties and methods with "is" or similar prefixes.
Ex: private bool _isFinished
12. Namespace names should follow the standard pattern
<company name>.<product name>.<top level module>.<bottom level module>
13. Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.
There are 2 different approaches recommended here.
1. Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.
2. Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.
Control | Prefix |
Label | Lbl |
TextBox | Txt |
DataGrid | Dtg |
Button | Btn |
ImageButton | imb |
Hyperlink | Hlk |
DropDownList | ddl |
ListBox | lst |
DataList | Dtl |
Repeater | rep |
Checkbox | Chk |
CheckBoxList | cbl |
RadioButton | rdo |
RadioButtonList | rbl |
Image | Img |
Panel | pnl |
PlaceHolder | phd |
Table | tbl |
Validators | val |
14. File name should match with class name.
For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)
15. Use Pascal Case for file names.
1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.
2. Comments should be in the same level as the code (use the same level of indentation).
Good:
// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
Not Good:
// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
3. Curly braces ({}) should be in the same level as the code outside the braces.
4. Use one blank line to separate logical groups of code.
Good:
bool SayHello ( string name )
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something // ...
return false;
}
return true;
}
Not Good:
bool SayHello (string name)
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something // ...
return false;
}
return true;
}
5. There should be one and only one single blank line between each method inside the class.
6. The curly braces should be on a separate line and not in the same line as if, for etc.
Good:
if ( ... )
{
// Do something
}
Not Good:
if ( ... ) {
// Do something }
7. Use a single space before and after each operator and brackets.
Good: if ( showResult == true )
{
for ( int i = 0; i < 10; i++ )
{ // }
}
Not Good:
if(showResult==true)
{
for(int i= 0;i<10;i++)
{
//
}
}
8. Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.
9. Keep private member variables, properties and methods in the top of the file and public members in the bottom.
THE FOLLOWING TABLE SUMMARIZES THE CAPITALIZATION RULES AND PROVIDES EXAMPLES FOR THE DIFFERENT TYPES OF IDENTIFIERS:
IDENTIFIER |
CASE |
EXAMPLE |
Class | Pascal | AppDomain |
Enum type | Pascal | ErrorLevel |
Enum values | Pascal | FatalError |
Event | Pascal | ValueChange |
Exception class | Pascal | WebException Note Always ends with the suffix Exception. |
Read-only Static field | Pascal | RedValue |
Interface | Pascal | IDisposable Note Always begins with the prefix I. |
Method | Pascal | ToString |
Namespace | Pascal | System.Drawing |
Parameter | Camel | typeName |
Property | Pascal | BackColor
|
Protected instance field | Camel | redValue Note Rarely used. A property is preferable to using a protected instance field. |
Public instance field | Pascal | RedValue Note Rarely used. A property is preferable to using a public instance field. |