Best Practices Of Writing C# Code

Anyone can write code with a few months of programming experience. But some developers know the coding standard and naming convention but not everyone follows the best practices

Anyone can write  code with a few months of programming experience. But only a few developers know what  coding standards and naming conventions are,  but not everyone follows best practices.

Introduction

In this article, we will learn what the coding standards and naming conventions are in C#. Firstly, you might wonder:

What is the definition of good code?

Answer
According to me, when the code is more understandable, readable, maintainable, reviewed and reused are the main characteristics of good code.

Review Code

This is the major point of code review. Inside it, review the code to make sure that the code follows the coding standard.

Naming Conventions
  1. Pascal Case
  2. Camel Case
Pascal Case

The first characters of all words are Upper Case and other characters are lower case.

Example

CaseHistory

Camel Case

The first letter is in lowercase and the first letter of every subsequent concatenated word is in caps.

OR

The first character of all words, except the first word, is Upper Case and other characters are lower case.

Example

businessCase

Naming Conventions and Standards

Use Pascal casing for Class names.

Example
  1. public class BusinessCase  
  2. {  
  3. //.........  
  4. }  
 Use Pascal casing for Method names.

Example
  1. void AutoComplete(string name)  
  2. {  
  3. // ......  
  4. }  
Use Camel casing for variables and method parameters.

Example
  1. int totalCount = 0;  
  2. void AutoComplete(string name)  
  3. {  
  4.    string fullMessage = "Hello " + name;  
  5. }  
Use Meaningful, descriptive words to name variables. Do not use abbreviations.

Example
  1. Good:  
  2. string address;  
  3. int salary;  
  4. Bad:  
  5. string nam;  
  6. string addr;  
  7. int sal;  
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.

Example
  1. for (int i = 0; i < count; i++)  
  2. {  
  3.    //...........  
  4. }  
Do not use underscores (_) for local variable names.

Prefix boolean variables, properties, and methods with "is" or similar prefixes.
  1. Ex: private bool _isFinished  

Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.

Use appropriate prefix for each of the UI elements. A brief list is given below.
 
Example

Control Prefix
Label lbl
TextBox txt
DataGrid dtg
Button btn
ImageButton imb

Use Pascal Case for file names.

Indentation and Spacing

Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.

Comments should be in the same level as the code (use the same level of indentation).

Example

Good
  1. // Format a message and display  
  2. string fullMessage = "Hello my name is " + name;  
  3. DateTime currentTime = DateTime.Now;  
  4. string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();  
  5. MessageBox.Show( message );  

Bad

  1. // Format a message and display  
  2. string fullMessage = " Hello my name is " + name;  
  3. DateTime currentTime = DateTime.Now;  
  4. string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();  
  5. MessageBox.Show ( message ); 
Curly braces ( {} ) should be in the same level as the code outside the braces.

Use one blank line to separate logical groups of code.

Example

Good
  1. bool ShowMessage(string name) {  
  2.     string fullName = "Hello " + name;  
  3.     DateTime currentTime = DateTime.Now;  
  4.     string message = fullName + ", the time is : " + currentTime.ToShortTimeString();  
  5.     MessageBox.Show(message);  
  6.     if (...) {  
  7.         // Write your code here  
  8.         // ...  
  9.         return false;  
  10.     }  
  11.     return true;  
  12. }  
Bad
  1. bool ShowMessage(string name) {  
  2.         string fullName = "Hello " + name;  
  3.         DateTime currentTime = DateTime.Now;  
  4.         string message = fullName + ", the time is : " + currentTime.ToShortTimeString();  
  5.         MessageBox.Show(message);  
  6.         if (...) {  
  7.             // Write your code here  
  8.             // ...  
  9.             return false;  
  10.         }  
  11.         return true;  
There should be one and only one single blank line between each method inside the class.

The curly braces should be on a separate line and not in the same line as if, for, etc.

Example

Good
  1. if ( ... )  
  2. {  
  3.    // write your code here  
Bad
  1. if ( ... ) {  
  2. // Write your code here }  
Use a single space before and after each operator and brackets.

Example

Good
  1. if(showResult)  
  2. {  
  3. for ( int i = 0; i < 10; i++ )  
  4. {  
  5. //  
  6. }  
  7. }  
Bad
  1. if(showResult==true)  
  2. {  
  3. for(int i= 0;i<10;i++)  
  4. {  
  5. //  
  6. }  
  7. }  
Superb Programming Practices

Method name should clarify the meaning. Do not use misleading names. If the method name is clear then there is no need of documentation.

Example

Good
  1. void SaveStudentDetails (string studentDetails )  
  2. {  
  3.    // Save the student details.  
  4. }  
Bad
  1. // This method will save the student details.  
  2. void SaveDetails (string student )  
  3. {  
  4.    // Save the student details.  
  5. }  
A method should do only one job at a time. Do not use it for more than one job.

Example

Good
  1. //Save student details  
  2. SaveStudentDetails();  
  3. //Send email to user that student details is added successfully.  
  4. SendEmail();  
Bad
  1. //Save student details  
  2. Public void SaveStudentDetails()  
  3. {  
  4.    // First task  
  5.    //Save student details  
  6.    //Second task  
  7.    // Send emails  
  8. }  
Make sure string comparisons convert string to uppercase or lowercase for comparison.

Example

Good
  1. If(UserName.ToLower()=="tom")  
  2. {  
  3.    // write yor logic here  
  4. }  

Bad

  1. If(UseName=="TOm")  
  2. {  
  3. //  
  4. }  
Comments
  • Do not write comments for every line of code and every variable declared.
  • Use // or /// for comments. Avoid using /* … */
  • Write comments where is it required. But they should be good readable and limited. If all variables and method names are perfectly meaningful, then there is no need of many comments.
  • If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.
  • Make sure to perform spelling check on comments and make sure proper grammar and punctuation is used.
Enum

Always use a singular noun for defining enum.

Example
  1. Enum Mailtype  
  2. {  
  3.    Subject,  
  4.    Body,  
  5.    PlaneText  
  6. }  
Interface

Always use the letter "I" as a prefix with the name of an interface. After letter I, use PascalCase.

Example
  1. public interface IMultiply  
  2. {  
  3.    int Multiplication();  
  4.  
Conclusion

In this article, I have shown you how to use C# coding standards and naming conventions. I hope you understood and liked it.