Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

C# Best Practices

DZone's Guide to

C# Best Practices

We take a look at some key concepts, and the code to implement them, in order to make your C# code as good as it can be.

· Web Dev Zone ·
Free Resource

Building real-time chat? Enroll in a Free Course on Mobile Chat Development. 

Introduction 

In this post, we’ll learn about some best practices with C# which we should follow to write better, more professional code.

For me, there are two main golden rules to follow in order to achieve good coding standards.

  1. Naming conventions.
  2. Optimizing syntax.

Now, we are going to go through each above point in detail.

Naming Conventions

Naming conventions refers to how we should declare variables.

Note: We should always use camel case while declaring variables, like var itemList = new List<T>();

 To declare a variable which returns a single entity/object, use the following convention:

var item = new Item();  

To declare a variable which returns multiple entities/objects, one needs to add "s" or "List" suffix, so we can easily identify that it will return a list of classes/objects.

var items = new List<Item>();   
//or  
var itemList = new List<Item>();  

To declare a private variable, we use an underscore (_).

private int _value = 10;  

Naming Conventions Table

 Name  Case
Variables  camelCase
 Class  PascalCase
Constructor PascalCase
Properties PascalCase
Delegate PascalCase
Enum PascalCase
Arguments in methods camelCase
Method PascalCase
Constants PascalCase
Field camelCase

Optimize Syntax

To declare an empty method which only returns a view in the MVC, we should use the expression body. 

//Avoid  
public ActionResult Dashboard()  
{  
    return View();  
}  

//Do  
public ActionResult Dashboard() => View(); 

To check for null or empty conditions, use the following:

//Avoid  
var varName = "faisal";  
if (varName != null && varName != "")  
{  
   //code  
}  

//Do  
var varName = "faisal";  
if (!string.IsNullOrEmpty(varName))  
{  
    //code  
}  

Below is how to use the null coalescing expression:

Test test = new Test();  

//Avoid  
var varName = test.Name != null ? test.Name : "";  

//Do  
var varName = test.Name ?? ""; 

Below is how to use the object initializer:

//Avoid  
Test test = new Test();  
test.Id = 1;  
test.Name = "faisal";  

//Do  
var test = new Test  
{  
   Id = 1,  
   Name = "faisal"  
};  

Below is how to use the ?. operator:

//Avoid  
var empName = "";  
Session["Name"] = "Faisal Pathan";  
if (Session["Name"] != null)  
{  
   empName = Session["Name"].ToString();  
}  
else  
{  
     empName = "";  
}  

//Do  
var empName = "";  
Session["Name"] = "Faisal Pathan";  
empName = Session["Name"]?.ToString() ?? "";

Avoiding extra braces is also a practice to get into.

Note: Only work with single line statements. 

var count = 10;  

//Avoid  
 if (count > 0)  
{  
   //code  
   count++;  
}  


//Do  
 if (count > 0) count++; //code  


//Avoid  
for (int i = 0; i < count; i++)  
{  
   //code  
   count += 10;  
}  

//Do  
for (int i = 0; i < count; i++) count += 10;  


var testList = new List<Test>();  
var names = new ArrayList();  

//Avoid  
foreach (var item in testList)  
{  
   names.Add(item.Name);  
}  

//Do  
foreach (var item in testList) names.Add(item.Name);

Below is how to use string interpolation.   

Test test = new Test();  

//Avoid  
 var details = string.Format("{0}, you are welcome, Your Id is {1}", test.Name , test.Id + "_emp");  

//Do  
var details = $"{test.Name}, you are welcome, Your Id is {test.Id}_emp";

This last code block demonstrates how to use the new lightweight switchcase introduced in C# 8, 

int itemSwitch = 1;  

//Good  
switch (itemSwitch)  
{  
 case 1:  
 Console.WriteLine("Item 1");  
 break;  
 case 2:  
 Console.WriteLine("Item 2");  
 break;  
 default:  
 Console.WriteLine("Item case");  
 break;  
}  

//better  
 var message = itemSwitch switch   
            {  
                1 =>  Console.WriteLine("Item 1"),  
                2 =>  Console.WriteLine("Item 2"),  
                2 =>  Console.WriteLine("Item 3")  
            };

Please give your valuable feedback/comments/questions about this article below. Please let me know how you like this article and how I could improve it.

Power realtime chat, IoT and messaging apps at scale. Pubsub realtime messaging, functions, chat, presence, push, notifications, blocks catalog and more.

Topics:
c# coding standards ,web dev ,c# tutorial ,coding standards

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}