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

Important Tips to Write Clean Code in C#

DZone's Guide to

Important Tips to Write Clean Code in C#

Writing clean code that follows industry standards is always a good idea. But it's usually easier said then done. Read on for overview of writing clean code.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

I remember those days when I started my career in programming. I struggled to write a piece of code and who cared for the coding standards at that time. As time went on, I got abetter command over programming and was able to think of particular scenarios to solve problems. From the start of my career until today, I have found a continuity, and that is learning. At that stage, I was learning to manage basic things and, now, I am learning to handle the problems. So, in life, learning is a never-ending process. Every day, we learn something, whether it's from reading articles, watching videos, or by our own mistakes or success in this programming environment.

As per my experience, we should not write our code like a layman. We should follow some coding standards to write clean, reusable, readable, and maintainable code.

I don't know exactly how many people are following coding standards. Even I was not perfectly following the coding standards. However, here are some of the coding guidelines that I used to follow.

Image title

To develop a reusable, reliable, readable, well-structured, and maintainable application, we must follow coding standards. There are several coding practices in the software industry. None of them are good or bad but the main thing is that whatever approach we follow, we should make sure that everyone working on that codebase follows the same standard.

Code Smell

Code smell is a technical word used to describe the quality of code - how a programmer writes their code.

Code smell is often a word used to describe code that you don't like. In that sense, it is synonymous with ugly, dirty, unclean, repeated, etc. Even though these types of code work just fine, they are hard to handle and maintain. There are a few reasons why our code smells.

  1. Duplicate code.
  2. Methods are too big.
  3. Classes with too many instance variables.
  4. Classes with too much code.
  5. Lazy class/freeloader.

Now, let's see how we can write clean code and avoid these smells in our program. Let's begin our discussion with the most basic coding standard, that is, Naming Conventions.

While we are coding, we shall focus on our naming standard. There are two main types of naming standards that we are using these days.

  • Pascal Casing: A word with the first letter capitalized, and the first letter of each subsequent word-part capitalized. Ex: CustomerName, EmployeeDetails, Salary, etc.
  • Camel Casing: A word with the first letter lowercase, and the first letter of each subsequent word-part capitalized. Ex: customerName, employeeDetails, salary.

Let's see where we will use which type of casing.

Always write class names and method names in Pascal casing.

public class EmployeeDetails  
  {  
      .......  

  }  

Now, this is how we declare methods inside a class.

public class EmployeeDetails  
 {  
     public void GetEmployeeSalary()  
     {  
         ---------------  

     }  


 }  

Always use variables and parameter names in Camel casing.

public class EmployeeDetails  
  {  
      private int totalSalary = 0;  
      public void GetEmployeeSalary( int employeeId)  
      {  
          int amount = 30000;  


      }  


  }  

Always use the letter "I" as a prefix with the name of the interface. After the letter "I", use Pascal case.

using System;  


namespace cleanacode  
{  
    interface IEmployee  
    {  
        void GetDetails();  
    }  
}  

Use meaningful variables and method names while coding. These names should be self-descriptive.

For this, I have created two samples of code. Check the first piece of code. Do you think this code will work effectively for maintenance and code review purposes?

 public class EmployeeDetails  
    {  

        public void GetSalary(int x, int p)  
        {  
            int z = x + p;                                             


        }  
}  

Image title

When a new developer checks this code, will they understand? Now, check the same piece of code that is well organized and follows coding standards.

public class EmployeeDetails  
    {  

        public void GetEmployeeSalary( int salary, int bonus)  
        {  
            int totalSalary = salary + bonus;  


        }  


    }  

Image title

Always rename the variables with a descriptive name. Don't use an unnecessary name for any variable so that it will be easy to maintain.

Whenever you are writing any method, always try to write the purpose of the method. Use summary or normal comments to specify the purpose of methods with the short description of parameters.

Here, in this example, we will show how to use this.

Image title


So, you can use summary by writing three forward slashes in VS.

public class EmployeeDetails  
    {  
        /// <summary>  
        /// To calculate total salary.  
        /// </summary>  
        /// <param name="salary"></param>  
        /// <param name="bonus"></param>  

        public void GetEmployeeSalary( int salary, int bonus)  
        {  
            int totalSalary = salary + bonus;  


        }  


    }  

Don't use a long method in the project. If by any chance you are using the long method, please use the region to make it easy to understand.

/// <summary>  
        /// To calculate total salary.  
        /// </summary>  
        /// <param name="userId"></param>  
        /// <param name="bonus"></param>  
        /// <param name="noOfDays"></param>  
        /// <param name="tax"></param>  
        /// <param name="deduction"></param>  

        public void GetEmployeeSalary(string userId,int bonus,int noOfDays,float tax,float deduction)  
        {  
            float bsal;  
            float hra;  
            float da;  
            float pf;  
            float extra;  
            float total;  

            #region BasicSalary  

            float monthlySalary = EmployeeDetails.GetSalary("UI54");  
            float basicSalary = monthlySalary + bonus;  


            #endregion  

            #region Calculate PF  
            pf= 15 * basicSalary / 100;  


            #endregion  

            #region Calculate HRA  

            hra= 20 * basicSalary / 100;  

            #endregion  

            #region Extra  

            extra = 2 * basicSalary / 100;  

            #endregion  

            #region Netsalary after deduction  

            total = basicSalary - (pf + hra + extra);  

            #endregion  



        }  
        /// <summary>  
        /// getting user salary  
        /// </summary>  
        /// <param name="userId"></param>  
        /// <returns></returns>  
        public static int GetSalary(string userId)  
        {  
            if (userId=="UI100")  
            {  
                return 60000;  
            }  
            else  
            {  
                return 45000;  
            }  


        }  

Now, if we press CTRL+M+O, it will minimize the window and we will get an output like this.

Image title

So, if you want to define a region, you can define your region by using the # symbol.Image title

Remove unnecessary namespace from your class. Writing unnecessary namespace will slow down your IntelliSense capacity to load all the classes, methods, etc. So, by removing these namespaces, you can increase your IntelliSense performance.

In big projects, it will be very difficult to identify which references are refered to in the class. So you can remove this using the following method.
Image title

This option will remove all the unnecessary namespaces used in the class. The main benefit of removing 'Usings' from the projects are:

  • Clean code.
  • IntelliSense runs faster as there are fewer things to search from the namespaces.

While working with HTML or ASP.NET, use proper formatting of your code, otherwise, it will look confusing and messy.

Image title

To format your section, right click on any particular section and then select Format Section. This will display your code in a well-organized manner.

Image title

So, these are some of the primary steps we need to follow for writing clean code.

Now, let's look at some third party tools like ReSharper and StyleCop, and find out how we can write clean and consistent code in our project.

Before exploring ReSharper, let's check look at what it is.

ReSharper is a refactoring tool for Visual Studio which helps in finding compiler errors, runtime errors, redundancies, and code smells right as you type, suggesting intelligent corrections for them. It helps to follow coding standards throughout the project. For using ReSharper, we need to download the ReSharper from here.

Image title

Initially, it comes with a 30-day trial and this is enough time to check out this product. Now, download and install.

Image title

After this, click Continue to install it completely.

Image title

After complete installation, close the Visual Studio instance and open it again. Once you open a new instance and open any project, you will find the ReSharper option in the top right.

Image title

Now, let's check how we can improve our coding standard using ReSharper. To find all your compiler errors, runtime errors, redundancies, you have to follow this option. 

Image title

Now, finally, a window will open which shows all your coding issues.

Image title

So solving these issues is very easy. It provides quick-fixes for most errors and other detected code issues. Also, it helps you to improve code instantly.

If you want to check out these naming rules, just go to ReSharper - Options - C# and check the following things.

Image title


Besides these, it helps in showing the architecture diagram of the whole project. To check the architecture diagram, please do the following steps. ReSharper - Architecture - Show project dependency Diagram.

Image title

Anyhow, this offers a lot of code refactoring techniques when you start working on it. You will know more about it. To learn more about using ReSharper, please check the following link.

Similarly, we have one more refactoring tool called StyleCop. This is a free tool. To use this, you have to download and install this StyleCop.

StyleCop provides value by enforcing a common set of style rules for C# code. StyleCop will continue to ship with a single, consistent set of rules, with minimal rule configuration allowed.

You can find the download link here.

After downloading, please install this. Once you have successfully installed SytleCop, restart Visual Studio. Right-click on your project and you will see the following context menu. 

Image title

 StyleCop settings define the rules you need to implement on your projects.

Image title

If you want to see any rules from here, you need to expand it. Then you will find the overview of the rule.

Image title

Now, to see all code issues, just run StyleCop.

Image title

Now, click on the output tab to show the warning.

Image title


In this way, we can use StyleCop and ReSharper for writing clean code and to follow coding standards throughout the project.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
c# ,resharper ,clean code ,web dev ,code analysis tools

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}