Click here to Skip to main content
Licence CPOL
First Posted 7 Apr 2007
Views 91,519
Bookmarked 43 times

Coding Standards for C#: Names

By | 7 Apr 2007 | Article
Comprehensive and essential facts which we developers sometimes neglect in C#

Introduction

When I was looking for a standard convention for generics, I came across a 50-page manual for coding standards for C#. I am sure that, apart from the author, there are few who actually go through and read all of them. So, I thought of coming up with this article. I have tried to comprehend the essential facts which we developers sometimes neglect in C#. I will also discuss some common pitfalls.

Small, sweet and simple.

That's how I describe it. I hope you enjoy reading.

Why Coding Standards

Simple: maintainability. If, 6 months down the line, your customer isn't too happy with the product and wants an enhancement in the application you have created, you should be able to do it without introducing new bugs. There are a lot of other good reasons, but this is the one which concerns us more than anything else.

Not following any standard is like going with a temporary solution (which might lead to a permanent problem) and, as you will see, it takes less effort to keep in mind a few simple measures than to do haphazard coding.

All you have to do is study good standards once and keep them in the back of your head. Trust me; it's worth it.

Contents

  1. Naming - What is meant by meaningful names
  2. Casing - When to use PascalCase and when camelCase
  3. Generics - Proper usage
  4. Delegates - Proper usage
  5. Miscellaneous - Some short tidbits
  6. Common Pitfalls - Mistakes we should watch out for
  7. References - Where to get more information

Naming

"The beginning of wisdom is to call things by their right names" - Chinese Proverb

"Meaningful" is the keyword in naming. By meaningful names, I mean concise names that accurately describe the variable, method or object. Let's see how this would be in C#:

Namespaces - Names should be meaningful and complete. Indicate your company or name, product and then your utility. Do not abbreviate.

//Good
namespace CompanyName.ProductName.Utility

//Bad
namespace CN.PROD.UTIL

Classes - Class names should always be a noun and, again, should be meaningful. Avoid verbs.

//Good
class Image
{
   ...
}
class Filters
{
   ...
}

//Bad
class Act
{
   ...
}
class Enhance
{
   ...
}

Methods - Always use a verb-noun pair, unless the method operates on its containing class, in which case, use just a verb.

//Good
public void InitializePath();
public void GetPath();
public void ShowChanges();
public void System.Windows.Forms.Form.Show();

//Bad
public void Path();
public void Changes();

Methods with return values - The name should reflect the return value.

//Good
public int GetImageWidth(Bitmap image);

//Bad
public int GetDimensions(Bitmap image);

Variables - Do not abbreviate variable names. Variable names should again be descriptive and meaningful.

//Good
int customerCount = 0;
int index = 0;
string temp = "";

//Bad
int cc = 0;
int i = 0;
string t = "";

Private member variables - Prefix class member variables with m_.

public class Image
{
   private int m_initialWidth;
   private string m_filename;
   ...
}

Interfaces - Prefix all interface names with I. Use a name that reflects an interface's capabilities, either a general noun or an "-able".

interface IClock
{
   DateTime Time { get; set; }
   ...
}

interface IAlarmClock : IClock
{
   void Ring();
   DateTime AlarmTime { get; set; }
   ...
}

interface IDisposable
{
   void Dispose();
}

interface IEnumerable
{
   IEnumerator GetEnumerator();
}

Custom attributes - Suffix all attribute class names with Attribute. The C# compiler recognizes this and allows you to omit it when using it.

public class IsTestedAttribute : Attribute
{
   public override string ToString()
   {
      return "Is Tested";
   }
}

//"Attribute" suffix can be omitted
[IsTested]
public void Ring();

Custom exceptions - Suffix all custom exception names with Exception.

public class UserNotExistentException :
    System.ApplicationException
{
   ...
}

Delegates - Suffix all event handlers with Handler; suffix everything else with Delegate.

public delegate void ImageChangedHandler();
public delegate string StringMethodDelegate();

Casing

C# standards dictate that you use a certain pattern of Pascal Casing (first word capitalized) and Camel Casing (all but first word capitalized).

Pascal Casing - Use PascalCasing for classes, types, methods and constants.

public class ImageClass
{
   const int MaxImageWidth = 100;
   public void ResizeImage();
}

enum Days
{
   Sunday,
   Monday,
   Tuesday,
   ...
}

Camel Casing - Use camelCasing for local variables and method arguments.

int ResizeImage(int imageCount)
{
   for(int index = 0; index < imageCount; index++)
   {
      ...
   }
}

Generics

Generics, introduced in .NET 2.0, are classes that work uniformly on values of different types.

Use capital letters for types; don't use "Type" as a suffix.

//Good
public class Stack ‹T›

//Bad
public class Stack ‹t›
public class Stack ‹Type›

Delegates

Use delegate inference instead of explicit delegate instantiation.

public delegate void ImageChangedDelegate();
public void ChangeImage()
{
   ...
}

//Good
ImageChangedDelegate imageChanged = ChangeImage;

//Bad
ImageChangedDelegate imageChanged =
    new ImageChangedDelegate(ChangeImage);

Use empty parenthesis on anonymous methods without parameters.

public delegate void ImageChangeDelegate();
ImageChangedDelegate imageChanged = delegate()
{
   ...
}

Miscellaneous

  • Avoid putting using statements inside a namespace
  • Check spelling in comments
  • Always start left curly brace { on a new line
  • Group framework namespaces together; add custom and thirdparty namespaces below
  • Use strict indentation (3 or 4 spaces, no tabs)
  • Avoid fully qualified type names
  • Indent comment at the same line as the code
  • All member variables should be declared at the top of classes; properties and methods should be separated by one line each
  • Declare local variables as close as possible to the first time they're used
  • File names should reflect the classes that they contain

Common Pitfalls

Let's face it, we all do these things one time or another. Let's avoid them as best as we can:

Names that make sense to no one but ourselves.

string myVar;
MyFunction();

Single or double letter variable names (this is excusable for local variables).

int a, b, c, a1, j1, i, j, k, ii, jj, kk, etc.

Abstract names.

private void DoThis();
Routine48();
string ZimboVariable;

Acronyms.

//AcronymFunction
AF();
//SuperFastAcronymFunction
SFAT()

Different functions with similar names.

DoThis();
DoThisWillYa();

Names starting with underscores. They look cool, but let's not ;)

int _m1 = 0;
string __m2 = "";
string _TempVariable = "";

Variable names with subtle and context-less meanings.

string asterix = "";
// (this is the best function of all)
void God()
{
   ...
}

Abbreviations.

string num;
int abr;
int i;

References

And Thanks

For reading this far. I am looking forward to your valuable suggestions. Take care!

History

  • 7th April, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

LakshmiChava

Web Developer

United States United States

Member

Biography Whats that ?
lots to do so less time

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberAteşG2:13 26 Sep '11  
GeneralMy vote of 3 Pinmemberhfrmobile3:43 19 Jan '11  
QuestionAre there any standards to cover project structures? Pinmembermidspace17:15 11 Jan '10  
AnswerRe: Are there any standards to cover project structures? Pinmemberhfrmobile3:49 19 Jan '11  
General.NET Design Guidelines for Class Library Developers Pinmemberjames.e.welch11:54 9 Apr '07  
GeneralRe: .NET Design Guidelines for Class Library Developers Pinmemberdnh5:39 16 Apr '07  
GeneralLiked it PinmemberQuartz.8:37 9 Apr '07  
GeneralRe: Liked it PinmemberDeepWaters11:09 11 Apr '07  
QuestionThis is okay? PinmemberSyed M Hussain12:29 8 Apr '07  
AnswerRe: This is okay? Pinmemberinetfly1232:13 9 Apr '07  
AnswerRe: This is okay? PinmemberSDragon424:21 9 Apr '07  
AnswerRe: This is okay? PinPopularmemberDeepWaters11:08 11 Apr '07  
GeneralMethod parameters PinmemberComplexityChaos3:26 8 Apr '07  
GeneralRe: Method parameters Pinmemberli_robert4:28 8 Apr '07  
GeneralRe: Method parameters PinmemberSDragon424:10 9 Apr '07  
GeneralSome comments PinmemberJohn C. Turner20:40 7 Apr '07  
  1. Namespaces - "Indicate your company or name, product and then your utility." This is nonsense. What if I have code that I use in several products? Which product name do I use? Or do I concatenate the product names?
  2. Methods with return values - "The name should reflect the return value." So why do you use "GetDimensions" instead of "GetDimension"? The method is only returning one value.
  3. Do not abbreviate variable names - "Good: index = 0; Bad: int i = 0;". Give me a break. How is "index" more meaningful than "i"? Moreover, later in the article you state "Single or double letter variable names [are] excusable for local variables". Not too consistent.
  4. Casing - You state that "C# standards dictate that you use a certain pattern of CamelCasing (first word capitalized) and pascalCasing (all but first word capitalized)." This is reversed of what it should be, and you then go on to talk about "PascalCasing" and "camelCasing".
  5. Indentation - "Use strict indentation (3 or 4 spaces, no tabs)". Does this mean that you allot time in all your projects to convert the Microsoft-supplied sample code from tabs to spaces? Absurd.
  6. spelling - You state this is your first article and you want to make a good first impression, so why didn't you spellcheck it? For something that aspires to be a "standard", it contains some glaring misspellings: bestest, privtae, stirng.
 
From reading your article, I would guess that you haven't spent much time trying to maintain other people's code. It's nonsense to include trivial code formatting issues in a coding standard - if you don't like the format, use Visual Studio's format command, or a 3rd party code beautifier. There have been times when I would have paid cash money for a decent comment in the middle of some dense code, but all you say about comments is to spellcheck them and line them up. There are many issues that you don't even mention, that contribute significantly to code reuse, portability and maintainability. Finally, there are tools available that check source code for compliance with company standards, and it would have been nice to see some mention of these too.
 
I would say that your article rating of 3+ is generous.
GeneralRe: Some comments PinmemberDeepWaters21:37 7 Apr '07  
QuestionReferencing class methods / variables PinmemberJamie Furtner20:22 7 Apr '07  
AnswerRe: Referencing class methods / variables PinmemberDeepWaters22:07 7 Apr '07  
AnswerRe: Referencing class methods / variables PinmemberKevmeister6819:15 17 Apr '07  
GeneralTwo more Rules PinsitebuilderUwe Keim20:09 7 Apr '07  
GeneralRe: Two more Rules PinmemberDeepWaters21:39 7 Apr '07  
GeneralChoose examples more carefuly Pinmemberdnh12:47 7 Apr '07  
GeneralRe: Choose examples more carefuly PinmemberDeepWaters13:13 7 Apr '07  
GeneralRe: Choose examples more carefuly Pinmemberdnh13:46 7 Apr '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 7 Apr 2007
Article Copyright 2007 by LakshmiChava
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid