DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • DevOps in Legacy Systems
  • Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
  • Understanding the Role of ERP Systems in Modern Software Development
  • Components of Container Management

Trending

  • DevOps in Legacy Systems
  • Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
  • Understanding the Role of ERP Systems in Modern Software Development
  • Components of Container Management
  1. DZone
  2. Data Engineering
  3. Data
  4. 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
·
Updated Mar. 13, 19 · Tutorial
Like (26)
Save
Tweet
Share
39.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.

Trending

  • DevOps in Legacy Systems
  • Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
  • Understanding the Role of ERP Systems in Modern Software Development
  • Components of Container Management

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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

Let's be friends: