Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

Important Tips To Write Clean Code In C# from Debendra Dash

- 02.02.19 | 22.11.19 - ErcanOPAK

To develop reusable, reliable, readable, well-structured, and maintainable application, we must follow the coding standard. 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 should follow the same standard.

Code Smell
Code Smell is a technical word used to describe the quality of code – how a programmer writes this code.

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

  1. Duplicated Code
  2. Methods 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 the programme. Let’s continue our discussion from the basic coding standard, that is, on Naming Convention.

While we are coding, we shall focus on our naming standard. There are 2 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 use class name and method name in Pascel 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 letter “I” as prefix with name of interface. After 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 maintainance and code review purposes?

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

When a new developer checks this code, what he will understand? Now, check the same piece of code with a well organized and good coding standard.

public class EmployeeDetails  
{  
        public void GetEmployeeSalary( int salary, int bonus)  
        {  
            int totalSalary = salary + bonus;  
        }  
}
Always rename the variables with a descriptive name. Don’t use unnecessary name for any variable so that it will be easy to maintain.

Whenever you are writting 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.

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 long method in the project. If by any chance you are using the long method, please use 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 minimze the window and we will get the output like this.


So, if you want to define region, you can define your region by #.

Remove unnecessary namespace from your class. Writing unnecessary namespace will slow down your intelliSense capacity to load all 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 referances are refered in the class. So you can remove this using the following way.

This option will remove all the unnecessary namespsces used in the class. The main benifit of removing Usings from the projects are-
  • Clean Code
  • IntelliSense runs faster as there are few things to search from the namespaces.

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

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.

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

Reference Article

Related posts:

Frozen Collections in C#: Immutable Performance for High-Speed Applications

Frozen Collections in C#: Immutable Performance for High-Speed Applications

C#: Use Index and Range Operators for Cleaner Array Slicing

C#: Use Index and Range Operators for Cleaner Array Slicing

C#: The Silent Rounding Bug From Using double Instead of decimal for Money

C#: The Silent Rounding Bug From Using double Instead of decimal for Money

Views: 145

Post navigation

How to make some specific word(s) Bold or Underline in ReportViewer
Tense Changes When Using Reported Speech

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com