Best .net coding standards - Part 1
Following are some of the best coding practices that we should follow to make our application up to the industry standard. This is just the first part of the long list. Please let me know if something needs to be added/deleted/modified here.
1. Keep it simple - each line should contain only one statement.
2. Boolean tests do not need to test for true.
WRONG:
If (succeeded == true) {Console.WriteLine("Passed");}
If (succeeded == false) {Console.WriteLine("Failed");}
RIGHT:
If (succeeded) {Console.WriteLine("Passed");}
If (!succeeded) {Console.WriteLine("Failed");}
3. If, if-else, if else-if else statements should look like this:
if (succeeded)
{
Console.WriteLine("Passed");
}
OR
if (condition)
{
Console.WriteLine("Passed");
}
else
{
Console.WriteLine("Failed");
}
OR
if (salary > 1000 && salary < 2000)
{
Console.WriteLine("Grade 1 employee");
}
else if (salary > 2000 && salary < 3000)
{
Console.WriteLine("Grade 2 Employee");
}
else
{
Console.WriteLine("Grade 3 Employee");
}
NOTE: use switch statements if the situation calls for it. Conditional statements need a default.
4. For / Foreach statements.
When using a data type that is not int, use foreach.
Examples:
for (int i = 0; i < 5; ++i)
{
Console.WriteLine(i);
}
or
single lined (consider using a while statement instead)
Syntax:
for (initialization; condition; update) ;
Example:
foreach (int i in IntList)
{
Console.WriteLine(i);
}
NOTE: Generally use brackets even if there is only one statement in the loop.
5. While/do-while statements.
A simple while statement example:
while (i > 0)
{
Console.WriteLine(i);
}
An empty while should have the following form:
while (i > 0) ;
A do-while statement should have the following form:
do
{
Console.WriteLine(i);
} while (i > 0);
6. Switch statements.
Example:
switch (grade)
{
case A:
Console.WriteLine(A);
break;
case B:
Console.WriteLine(B);
break;
default:
Console.WriteLine(N/A);
break;
}
NOTE: Each switch statement must have a default. Also, avoid switch statements in JavaScript, due to known performance problems.
7. Try-catch Statements.
Example:
try
{
int num = 10;
int result = num/0;
}
catch (DivideByZeroException) {}
or
try
{
int num = 10;
int result = num/0;
}
catch (Exception e)
{
Console.WriteLine(DivideByZeroException occured);
}
Or
try
{
Conn.Open();
int num = 10;
int result = num/0;
}
catch (Exception e)
{
Console.WriteLine(DivideByZeroException occured);
}
finally
{
Conn.Close();
}
a. Don't break by throwing exceptions, and only catch specific exception types that the code can handle. If a particular exception is caught then do something with it – at a minimum log it. Do not overuse try/catch - there is a performance penalty every time it's used.
b. Use try/parse when evaluating integers.
c. Don't rename an exception and then throw it – the stack trace will be lost.
d. Catch blocks should never be empty.