Saturday, March 1, 2014

C# coding conventions

Naming Conventions

  • Always use Camel case (A word with the first letter lowercase, and the first letter of each subsequent word-part capitalised) while declaring variables.
  • Use Pascal (A word with the first letter capitalised, and the first letter of each subsequent word-part capitalised) naming format while declaring Properties.
  • Avoid all uppercase or lowercase names for properties, variables or method names. Use all uppercase when declaring const variables.
  • Never use a name that begins with a numeric character.
  • Always prefer meaningful names for your class, property, method, etc. This will be very useful for you to maintain the code in future. For example, “P” will not give proper meaning for a class. You will find it difficult to know about the class. But if you use “Person”, you will easily understand by it.
  • Never build a different name varied by capitalisation. It is a very bad practice. It will not be useful while developing code, as you will not know what is “person” class and what is “Person” class!!! But from the above scenario, it can be very easily understandable that “person” is an instance variable of “Person” class.
  • Don't use the same name used in .NET Framework. People who are new to your code have great difficulty to understand it easily.
  • Avoid adding prefixes or suffixes for your identifiers. Though in some guidelines, they use “m_” and in some other they use “_” as the prefix of variable declaration. I think it is not that much useful. But, it depends on your organisational coding practices. This point is contradictory based on various organisations and there is no strict guidance on it.
  • Always use “I” as prefix for Interfaces. This is a common practice for declaring interfaces.
  • Always add “Exception” as suffix for your custom exception class. It will give better visibility to your exception class.
  • Never prefix or suffix the class name to its property names. It will unnecessarily increase the property name. If “Firstname” is a property of “Person” class, you can easily identify it from that class directly. No need to write “PersonFirstname” or “FirstnameOfPerson”.
  • Prefix “is”, “has” or “can” for boolean properties like “isVisible”, “hasChildren”, “canExecute”. These give proper meaning to the properties.
  • Don't add prefix for your controls, instead write proper name to identify the control.

Commenting Conventions
  • Place the comment on a separate line, not at the end of a line of code.
  • Begin comment text with an uppercase letter.
  • End comment text with a period.
  • Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.

Value types vs Reference types

  • If you want to store your data, use value types and when you want to create an instance of your type by defining the behavior, use reference types.

Value type

static void Main(string[] args)
{
int i = 5;
SetValues(i);
    // will print "Currently i = 5"
System.Console.WriteLine(
"Currently i = " + i);
}
static void SetValues(int x)
{
x +=
10;
}

Reference type

static void Main(string[] args)
{
int i = 5;
SetValues(
ref i);
    // will print "Currently i = 15"
System.Console.WriteLine(
"Currently i = " + i);
}
static void SetValues(ref int x)
{
x +=
10;
}

Need nullable data type ?

Simple data type

// simple declaration of int
int index = 0;

Nullable data type

// nullable data type declaration
int? index = null;

Runtime constants Vs Compile time constants

Runtime constants

// runtime constant
public readonly string CONFIG_FILE_NAME = "web.config";
  • must be initialised at the time of declaration and can’t be changed later.
  • limited to only numbers and strings.
  • it is a bit faster.

Compile time constants

// compile time constantpublic const string CONFIG_FILE_NAME = "web.config";
  • Runtime constants (readonly) are initialised in the constructor and can be changed at different initialisation time.
  • more reliable code.

Explicit casting Vs Implicit casting

Explicit

// this line may throw Exception if it is unable to downcast from Person to Employeevar employee = (Employee) person;

Implicit

It is better to use “is” and “as” operator while casting.
// check if the person is Employee typeif(person is Employee)
{
// convert person to Employee type employee = person as Employee;
}

Use string.Format() or StringBuilder for String Concatenation

Simple string concatenation

string str = "a";
str +=
"r";
str +=
"s";
Console.WriteLine(str);



Using string.Format()

string str = string.Format("{0}{1}{2}{3}{4}", "a", "r", "s");

Using StringBuilder

StringBuilder sb = new StringBuilder();
sb.Append(
"a");
sb.Append(
"r");
sb.Append(
"s");
string str = sb.ToString();

Use IDisposable Interface wherever possible
class BaseClass : IDisposable
{
}

It will help free up the class resources when unused.

Using lambda expressions

  • If you are defining an event handler that you do not need to remove later, use a lambda expression.  
  • Use lambda expressions wherever you can remove boilerplate code.

public Form2()
{
   
// You can use a lambda expression to define an event handler.
   
this.Click += (s, e) =>
       {
           MessageBox.Show(
               ((MouseEventArgs)e).Location.ToString());
       };
}

for() Vs foreach()

Prefer foreach over for, C# compiler generates the best iteration code for your particular collection.

Special Note

* Split your Logic in Several Small and Simple Methods



Further Secure Coding Guidelines



No comments :

Post a Comment