C# Coding Best Practices – Coding Conventions with Examples

C# Coding best practices ensure that your code is consistent, readable, understandable, and maintainable.

When it comes to writing quality code, there are the best C# coding standards a developer should follow to make the code cleaner and easy to maintain.

There are a few things you should keep in mind while writing C# code. In this article, we will learn the best coding practices every C# developer should follow.

Naming Conventions

Using standard naming conventions across the project can make it easier for programmers to understand the code and help avoid confusion. Always use standard and meaningful names of classes, methods and variables. Also, we should make sure to use Pascal or Caml case.

Pascal Case

Pascal is usually preferred for class, struct, method, property, or constant field.

class PilotClass
{
    public const string ProductName = "Laptop";
    public string EmployeeName { get; set; }
    public void GetEmployeeDetails()
    {
        //Write Logic here
    }
}

Camel Case

Further, the Camel case is mostly preferred for method arguments, private fields, and local variables.

public void GetEmployeeDetails(int employeeId)
{
   string empName = String.Empty;
}

Declaration of Empty String

We should avoid declaring a string with empty quotes because this is a bad coding practice. Have a look at the below code snippet.

string EmpName = ""; //Bad code writing practice

Instead, we should use String.Empty.

string EmpName = String.Empty; //Correct way to declare a string

Empty String check

Never check an empty string like this –

 string employeeName = string.Empty;
 if(employeeName == "")
 {
 }

Instead, we should use the code snippet.

if(string.IsNullOrEmpty(employeeName)) 
 { 
 
 }

String compare with user input

It is good practice to always convert string variables into either uppercase or lowercase before comparing them with the user input string.

Don’t write code like this.

 string employeeName = "Ram Kumar";
 string inputName = "ram kumar";
 if(employeeName == inputName) 
 { 
 
 }

Instead, use Good C# code Practice

It is a good practice to always convert string variables into either uppercase or lowercase before comparing them with user input.

if (employeeName.ToLower() == inputName.ToLower())
{

}

Check for Null or Empty Conditions

Always use string.IsNullOrWhiteSpace() method to check for null, whitespace, or empty string. This method returns true if the value is null, empty, or whitespace, and false if it contains some value.

This method checks whether the given string is null, empty, or contains white space characters only.

if(string.IsNullOrWhiteSpace(employeeName)) 
{ 
 
}

Use Meaningful Naming Conventions

Choose a meaningful name for the class, method, or interface of a variable.
A well-named entity means that it doesn’t need extra comments.

Don’t use single-letter variable names like a,b c. Use names as shown below.

int memberId;
string ProductName;
void SendNotification();

Additionally, you may use the below tips to follow industry standards.

  • Use Ctrl + k +d for proper formatting and indenting.
  • Always use the letter I before the name of an Interface. For Eg – IProductDetails, IEmployeeDetails

Proper Indentation and Formatting

Maintaining proper indentation and formatting makes our code much cleaner and easier to understand. Modern IDE, such as Visual Studio 2019, 2022 provides code formatting tools and inbuilt shortcuts.

Use NULL Conditional Operator

C# 6.0 introduces a null conditional operator. This operator allows us to access a property or object with no fear of null reference.

var name = employee?.basicInformation?.Name

Unit Testing

A code is at risk until it is properly tested. So, Unit Testing make sure to deliver a robust application. We can use any testing framework like MSTest, NUnit, and xUnit.

[TestMethod]
public void GivenTwoNumbers_ThenExpectSumResult()  
{
    var calc = new Calculator();
    var actulaResult = calc.AddNumber(10, 20);
    Assert.AreEqual(30, actulaResult);
}

Here, we are using the MSTest project. So, we are creating a method GivenTwoNumbers_ThenExpectSumResult() and this method calls the method AddNumber() of class Calculator. Finally, we are matching the result with Assert.AreEqual()

Visual Studio Extensions for Best Coding Practice

It would be helpful if you also use Visual Studio extensions because this will also guide you to follow the best coding practices. And, some of the famous extensions are.

  • Resharper
  • Prettier
  • Visual Studio Spell Checker

Conclusion

A coding practice ensures code readability and consistency within the project or application. There are a lot more coding practices in C# that help a developer to ensure good code quality. Hope, you like this article. Please write your feedback in the comment box.

Keep Following – SharePointCafe.Net

.NET documentation C# Coding Conventions – C# | Microsoft Learn

Leave a Comment

RSS
YouTube
YouTube
Instagram