DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > C# Best Practices

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.

Faisal Pathan user avatar by
Faisal Pathan
·
Mar. 13, 19 · Web Dev Zone · Tutorial
Like (26)
Save
Tweet
38.28K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Database Syntax (programming languages) Strings Blocks Operator (extension) Data Types Coding (social sciences)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Importance of Semantics for Data Lakehouses
  • Common Types Of Network Security Vulnerabilities In 2022
  • How Low Code Demands More Creativity From Developers
  • 8 Must-Have Project Reports You Can Use Today

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo