Click here to Skip to main content
15,867,986 members
Articles / Programming Languages / C#
Tip/Trick

C# - Naming Standards

Rate me:
Please Sign up or sign in to vote.
4.76/5 (15 votes)
30 Sep 2011CPOL4 min read 67.7K   19   11
C# - Naming Standards

Coding Standards for C#: Names


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.

C#
//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.
C#
//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.
C#
//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.
C#
//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_.
C#
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".
C#
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.
C#
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.
C#
public class UserNotExistentException :
    System.ApplicationException
{
   ...
}

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

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

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


C#
//Good

public class Stack ‹T›

//Bad

public class Stack ‹t›
public class Stack ‹Type›

Delegates


Use delegate inference instead of explicit delegate instantiation.
C#
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.
C#
public delegate void ImageChangeDelegate();
ImageChangedDelegate imageChanged = delegate()
{
   ...
}

Miscellaneous



  1. Avoid putting using statements inside a namespace
  2. Check spelling in comments
  3. Always start left curly brace { on a new line
  4. Group framework namespaces together; add custom and thirdparty namespaces below
  5. Use strict indentation (3 or 4 spaces, no tabs)
  6. Avoid fully qualified type names
  7. Indent comment at the same line as the code
  8. All member variables should be declared at the top of classes; properties and methods should be separated by one line each
  9. Declare local variables as close as possible to the first time they're used
  10. 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.


C#
string myVar;
MyFunction();

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

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

Abstract names.

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

Acronyms.
C#
//AcronymFunction

AF();
//SuperFastAcronymFunction

SFAT()

Different functions with similar names.
C#
DoThis();
DoThisWillYa();

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

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

Variable names with subtle and context-less meanings.
C#
string asterix = "";
// (this is the best function of all)

void God()
{
   ...
}

Abbreviations.

C#
string num;
int abr;
int i;

Tree Data Structure in C#


Here is a simple Tree data structure in C sharp.NET:
C#
using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms
{
    class Tree
    {
        private TreeNode root;
        public Tree()
        {
            root = null;
        }

        public TreeNode FindRecursive(TreeNode root, int dataValue)
        {
            if (root == null)
            { return null; }
            else if (root.DataValue == dataValue)
            { return root; }
            else if (root.DataValue < dataValue)
            { return FindRecursive(root.RightNode, dataValue);}
            else 
            { return FindRecursive(root.LeftNode, dataValue); 
            }
        }
        public TreeNode Find(int dataValue)
        {
            if (root == null)
            {
                return null;
            }
            else
            {
                TreeNode currentNode = root;
                while (currentNode != null)
                {
                    if (currentNode.DataValue == dataValue)
                    {
                        return currentNode;
                    }
                    else if (currentNode.DataValue < dataValue)
                    {
                        currentNode = currentNode.RightNode; 
                    }
                    else if (currentNode.DataValue > dataValue)
                    {
                        currentNode = currentNode.LeftNode; 
                    }
                    return null;
                }
                return null;
            }
        }
    }
    public class TreeNode
    {
        private int dataValue;
        private TreeNode leftNode = null;
        private TreeNode rightNode = null;

        public TreeNode(int data)
        {
            dataValue = data;
        }
        public TreeNode LeftNode
        {
            get
            {
                return leftNode;
            }
            set
            {
                leftNode = value;
            }
        }
        public TreeNode RightNode
        {
            get
            {
                return rightNode;
            }
            set
            {
                rightNode = value;
            }
        }
        public int DataValue
        {
            get
            {
                return dataValue;
            }
            set
            {
                dataValue = value;
            }
        }

    }
}

Check If Cycle exists in a Linked List.

Check if the linked list contains a cycle.


C#
using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms
{
    public class LinkedList
    {
        private Node head;

        public LinkedList()
        {
            head = null;
        }
       
        public bool CheckCycle()
        {
            Node step1Node = head;
            Node step2Node = head.NextNode;
            
            while (true)
            {
                if ((step2Node == null)||(step2Node.NextNode == null))
                    return false;
                else if ((step1Node.Equals(step2Node))||(step1Node.Equals(step2Node.NextNode)))
                    return true;
                else
                { 
                step2Node = step2Node.NextNode;
                step2Node = step2Node.NextNode;
                step1Node = step1Node.NextNode;
                }
            }
        }
        public int FindPosition(int data)
        {
            Node checkNode = head;
            int position = 1;
            int dataPosition = 0;
            while (checkNode != null)
            {
                if (checkNode.DataValue == data)
                {
                    dataPosition = position;
                }
                checkNode = checkNode.NextNode;
                position = position + 1;
            }
            return dataPosition;
        }
    }
    public class Node
    {
        private int dataValue;
        private Node nextNode = null;

        public Node(int data)
        {
            dataValue = data;
        }
        public Node NextNode
        {
            get
            {
                return nextNode;
            }
            set
            {
                nextNode = value;
            }
        }
        public int DataValue
        {
            get
            {
                return dataValue;
            }
            set
            {
                dataValue = value;
            }
        }
    }
}

Nth Element from the Last in a Linked List


Another advanced algorithm is to find the Nth Element from the LAST with the optimal performance.

Here is the implementation


C#
using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms
{
    public class LinkedList
    {
        private Node head;

        public LinkedList()
        {
            head = null;
        }

        public int FindNthElementFromLast(int m)
        {
            int n = m - 1;
            int returnValue = -1;
            if (n >= 0)
            {
                Node nthElement = head;
                Node currentElement = head;
                for (int i =0;i less than n;i++)
                {
                    if (currentElement.NextNode != null)
                    {
                        currentElement = currentElement.NextNode;
                    }
                    else
                    {
                        returnValue = -1;
                        return returnValue;
                    }
                }

                if (returnValue != -1)
                {
                    while (currentElement.NextNode != null)
                    {
                        currentElement = currentElement.NextNode;
                        nthElement = nthElement.NextNode;
                    }
                    returnValue = nthElement.DataValue;
                }
            }
            return returnValue; 
        }       
    }
    public class Node
    {
        private int dataValue;
        private Node nextNode = null;

        public Node(int data)
        {
            dataValue = data;
        }
        public Node NextNode
        {
            get
            {
                return nextNode;
            }
            set
            {
                nextNode = value;
            }
        }
        public int DataValue
        {
            get
            {
                return dataValue;
            }
            set
            {
                dataValue = value;
            }
        }
    }
}

Linked List SORT Algorithm


If you need a sort algorithm in Linked List, please check another implementation in my last blog.
C#
using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms
{
    public class LinkedList
    {
        private Node head;

        public LinkedList()
        {
            head = null;
        }

        public void Sort()
        {
            if (head != null)
            {
                int j = 0;
                Node MinElement = head;
                Node currentElement = MinElement.NextNode;
                while (currentElement != null)
                {
                   
                    if (currentElement.DataValue < MinElement.DataValue)
                    {
                        MinElement = currentElement;
                        Insert(MinElement.DataValue);
                        DeleteAtPosition(j+1);
                    }
                MinElement = MinElement.NextNode;
                }
            }
        }       
    }
    public class Node
    {
        private int dataValue;
        private Node nextNode = null;

        public Node(int data)
        {
            dataValue = data;
        }
        public Node NextNode
        {
            get
            {
                return nextNode;
            }
            set
            {
                nextNode = value;
            }
        }
        public int DataValue
        {
            get
            {
                return dataValue;
            }
            set
            {
                dataValue = value;
            }
        }
    }
}

Linked List in C#


I got tones of emails, lately for Linklist and Tree data structure implementation.

Here is a simple Linked List Data structure in C#. A LinkedList will always have two classes, a LinkedList class and a Node Class.
I have also included most common options to insert and Delete nodes.

C#
using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms
{
    public class LinkedList
    {
        private Node head;

        public LinkedList()
        {
            head = null;
        }
        public void Insert(int dataValue)
        {
            if (head == null)
            {
                Node nodeInsert = new Node(dataValue);
                head = nodeInsert;
                nodeInsert.NextNode = null;
            }
            else
            {
                Node nodeInsert = new Node(dataValue);
                nodeInsert.NextNode = head;
                head = nodeInsert;
            }
        }
        public void InsertAtPosition(Node insertNode, int i)
        {
            if (i == 0)
            {
                insertNode.NextNode = head;
                head = insertNode;
            }
            else
            {
                Node currentNode = head;
                Node currentNodeNext = head.NextNode;
                for (int j = 0; j < i; j++)
                {
                    currentNode = currentNode.NextNode;
                    currentNodeNext = currentNode.NextNode;
                }
                if (currentNode != null)
                {
                    currentNode.NextNode = insertNode;
                    insertNode.NextNode = currentNodeNext;
                }
            }
        }
        public void DeleteAtPosition(int i)
        {
            if (i == 0)
            {
                head = null;
            }
            else
            {
                Node currentNode = head;
                Node currentNodeNext = head.NextNode;
                for (int j = 0; j < i; j++)
                {
                    currentNode = currentNode.NextNode;
                    currentNodeNext = currentNode.NextNode;
                }
                if (currentNode != null)
                {
                    currentNode.NextNode = currentNodeNext.NextNode;
                }
            }
        }
        public bool Delete(Node nodeToDelete)
        {
            bool returnFlag = false;

            if (head == null)
                returnFlag = false;
            else if (head.Equals(nodeToDelete))
            {
                head = null;
                returnFlag = true;
            }
            else
            {
                Node checkNode = head;
                Node checkNodeNext = head.NextNode;
                while (checkNodeNext != null)
                {
                    if (checkNodeNext.Equals(nodeToDelete))
                    {
                        checkNode.NextNode = checkNodeNext.NextNode;
                        checkNodeNext = null;
                        returnFlag = true;
                    }
                }
            }
            return returnFlag;
        }
        public void Print()
        {
            Node firstNode = head;
            while (firstNode != null)
            {
                Console.Write(firstNode.DataValue + " ");
                firstNode = firstNode.NextNode;
            }
        }
        public void Clear()
        {
            Node checkNode = head;
            Node checkNodeNext;

            while (checkNode != null)
            {
                checkNodeNext = checkNode.NextNode;
                checkNode = null;
                checkNode = checkNodeNext;
            }
        }       
    }
    public class Node
    {
        private int dataValue;
        private Node nextNode = null;

        public Node(int data)
        {
            dataValue = data;
        }
        public Node NextNode
        {
            get
            {
                return nextNode;
            }
            set
            {
                nextNode = value;
            }
        }
        public int DataValue
        {
            get
            {
                return dataValue;
            }
            set
            {
                dataValue = value;
            }
        }
    }
}

License

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


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionPlagiarised Pin
Michael Lynch29-Sep-15 20:16
Michael Lynch29-Sep-15 20:16 
QuestionArticle character encoding Pin
Dan Stevens5-May-15 0:14
Dan Stevens5-May-15 0:14 
AnswerRe: Article character encoding Pin
osoviejo15-Aug-15 17:06
osoviejo15-Aug-15 17:06 
GeneralMy vote of 2 Pin
Toby_5-Dec-14 6:28
Toby_5-Dec-14 6:28 
GeneralMy vote of 3 Pin
Kishore Jangid5-Jan-13 9:06
Kishore Jangid5-Jan-13 9:06 
GeneralReason for my vote of 5 Excellent reference which I'll refer... Pin
Bryan Nystrom4-Oct-11 5:09
Bryan Nystrom4-Oct-11 5:09 
GeneralReason for my vote of 5 Good tip (in fact this could be an a... Pin
Karthik. A4-Oct-11 3:36
Karthik. A4-Oct-11 3:36 
GeneralReason for my vote of 4 "Always start left curly brace { on ... Pin
Clark Kent12329-Sep-11 9:01
professionalClark Kent12329-Sep-11 9:01 
GeneralRe: Using names that start with an underscore or not has nothing... Pin
Trellium8-Oct-11 8:35
Trellium8-Oct-11 8:35 
BugFindNthElementFromLast seems to have a problem Pin
John Whitmire6-Oct-11 10:50
professionalJohn Whitmire6-Oct-11 10:50 
Questionprivate member prefix? Pin
Member 81989025-Oct-11 3:48
Member 81989025-Oct-11 3:48 

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

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