Top 15 Best Coding Practices in C#

Hey buddy, Welcome to this article. I am pleased to share my insights over coding practices with you. Let me share my background, I have been working on .NET technology for last 6 years, so I believe, I have enough expertise to express my knowledge on C# and .NET. So, Let’s start, here is content outline for this article:

Content Outline

  1. Use “using” statement
  2. Use Exception Handling Properly
  3. Use LINQ for Data Manipulation
  4. Comment and Document Your Code
  5. Keep Methods Short and Focused
  6. Use string builder instead of String
  7. Use of “Var”
  8. Constructors
  9. Arrays Initialization
  10. && and || operators
  11. new operator
  12. Static members
  13. LINQ queries
  14. Comment style
  15. Implicitly typed local variables in LINQ

Use “using” statement

You should use “USING” statement to dispose resources when they are not needed or out of scope. This is useful when working with objects like database connection.

sample code:

using (var DatabaseConnection= new SqlConnection(connString))
{
    DatabaseConnection.Open();
}

Use Exception Handling Properly

While writing code, you have to know that you have to handle exceptions, even if there is low possibility of error. It will be better if exceptions are handling specifically, just like code below:

public void Test(int a, int b)
{
    try
    {
        int result = a / b;
        Console.WriteLine(result);
    }
    catch(DivideByZeroException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Use LINQ for Data Manipulation

  public void Test(List<string> inputNames)
 {
     // Not good practice
     List<string> namesThatContainS = new List<string>();
     foreach (var name in inputNames)
     {
         if (name.Contains("S"))
         {
             namesThatContainS.Add(name);
         }
     }

     // Better
     var namesThatContainS = inputNames.Where(n => n.Contains("S")).ToList();
 }

Comment and Document Your Code

Writing proper comments is necessary for readability and making sure that new developers will easily understand the code.

/// <summary>
/// This is the test function, which will check if input strings contain S then it will add those in list of strings
/// </summary>
/// <param name="inputNames"></param>
public List<string> Test(List<string> inputNames)
{           
    var namesThatContainS = new List<string>();
    foreach (var name in inputNames)
    {
        if (name.Contains("S"))
        {
            namesThatContainS.Add(name);
        }
    } 
    return namesThatContainS;
}

Keep Methods Short and Focused

Good practice code:

 public void Test()
 {
     Function1();
     Function2();
     Function3();
 }

It is not good practice to include lengthy functions or do large operation inside single function. Functions should be of size around 20-30 lines maximum.


Use string builder instead of String

StringBuilder represents a mutable string of characters.

var text = "saif";
var texts = new StringBuilder();
for (var j = 0; j < 500; j++)
{
    texts.Append(text);
}

Use of “Var”

Use var when you are using explicit instantiation, otherwise don’t use this in implicit instantiation, below is the example of that:

//Good Practice
var vowels2 = new string[] { "a", "e", "i", "o", "u" };

//Not Good Practice
var vowels1 = { "a", "e", "i", "o", "u" };

Constructors

Use camelCase for input parameter of constructor. Test is class name here for reference.

public Test(string primeNumber);

Arrays Initialization

//Use collection expressions
public int[] Numbers = { 1, 2, 3, 4 };

&& and || operators

Use && and || when you perform comparison in if/else statement specially

if (numberOne == numberTwo && (numberOne != 1 || numberTwo != 1))
{
}

new operator

// Good Practice
var car = new Car();
Car car2 = new();

//Equivalent
Car car3 = new Car();

Static members

Call static functions by using the class name (Test):

Test.StaticFunction();

LINQ queries

//Use meaning full names of result like below:
var carsOf2017 = cars.Where(car => car.YearMade == "2017");

Comment style

Use // for simple comments of one line.

Implicitly typed local variables in LINQ

Use var for LINQ query results to avoid writing out the full type.

var filteredNumbers = numbers.Where(n => n > 5).ToList();

Conclusion and Call to Action

So this is it, these are top 15 good practices so using C# best coding practices can significantly improve the software’s readability, maintainability, and efficiency. Begin applying these techniques to your projects and work to raise your code standards on a constant basis. Below are the useful links which you can explore for further reading and understanding of best coding practices. Have fun with your coding!


Useful Links

https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions

https://www.freecodecamp.org/news/coding-best-practices-in-c-sharp

https://dev.to/hbolajraf/c-best-practices-6dp

Scroll to Top