Best practices in developing C# applications

30 November 2020 at 10:00 by ParTech Media - Post a comment

In the modern-day computer world, performance and security play a major role in ensuring the user-friendliness of a website or an application. Similarly, for developers who program the application, a proper coding standard has to be practiced to ensure that all the developers who have access to the code can understand the code, make new changes on top of it, can debug, and figure out the issues.

If the code is not developed properly, it will be a cumbersome job for the developers who try to make changes on top of the code. It can even increase the man-hours spent on a task and may result in malfunctioning of the code. To avoid such issues and ensure that the standard is maintained, few best practices can be followed by the developers. Let's see some best practices in developing C# application in this post.

Table of contents

  1. Best practices in developing C# application
  2. Conclusion

Best practices in developing C# application

PascalCasing

The names of the Classes and methods should follow PascalCasing as it goes hand in hand with the Microsoft .Net framework and also makes it easier to read.

public class PartechClass

{

   public void GetPartechAddress()

   {

   }

}
 

In the above example, PartechClass and GetPartechAddress are the class and method respectively, which are written in the Pascal case.

CamelCasing

Similar to the classes and methods, local variables inside a method and parameters of the methods should be in camel casing.

public class PartechClass

{ 

   public void GetPartechAddress(int studentId)

   {

​      public string addressLine1 = string.Empty;

   }

}

In the above example, addressLine1 and studentId are the variables and input parameter of a method which are written in camel casing.

Predefined typenames

In order to make it consistent and more readable, it is always recommended to use the predefined type names instead of system type names

Predefined type names (recommended)

  • string address;
  • int number;

System type names (not recommended)

  • String address;
  • Int32 number;

Declaring variables

Declare all the variables at the top of the class. So that it will be easier for developers to find them when they want. Declaring the global variables in multiple places will result in a wild-goose chase later.

Also, declare the static variables before the global variables.

public class PartechClass

{

   public static string Username;

   public string AddressLine1 = string.Empty;

   public void GetPartechAddress(int studentId)

   {

   }

}

Align the curly braces

Vertically aligning the curly braces helps the developers to have an easy read and help them easily understand the beginning and the ending of a class, method, condition block, and loop blocks.

public class PartechClass

{ 

   public void GetPartechAddress(int studentId)

   {

​      public string addressLine1 = string.Empty;

 

​      if (!String.IsNullOrEmpty(addressLine1))

​      { 

​         //Area to enter core logic 

​      }

   }

}

Avoid underscores

It is recommended not to use underscores in the variable names, to increase the readability and consistency of the code.

public string user_name; //Not recommended

Interface naming convention

Similar to classes, it is recommended to follow Pascal casing for interfaces also. Along with that, the name of the interface is prefixed by I.

public interface IOperations 

{

}

Have valid method names

The name of the method should be able to convey the operation the method is going to carry out. Also, methods should do only a specific operation. Multiple operations should not be combined in a single method.

public class PartechFileOperations

{

   public string GetDataFromFile(string fileName)

   { 

​      //Operation to read data from a file. 

   }

}

In the above example, the method GetDataFromFile will be used to get the data from the file by passing the name of the file. By this, it becomes a method which can be commonly used to call from multiple places to get the data from the file.

Adding comments

Add comments on top of every method by mentioning what this method does and what is the expected input and output from the method.

And inside the method, add comments only at lines where they are very necessary, do not write comments for every line of code.

And for adding comments, use // or ///. Avoid using /.../.

Application logging

Logging is an essential process for an application to trace and figure out issues and errors. There are multiple logging frameworks available in C# for easy logging and maintenance.

Use Nullable data types as required

By default, C# doesn't allow to store null values in variables of type integer, double or Boolean. But, there would be scenarios encountered by the programmers to handle null values for the variables of the above-mentioned data types.

To handle this, C# provides an option to store the null values.

int? number = null;

On adding the ‘?’ Identifier to the data type, the variable 'number' will allow null values.

Use Runtime constants over compile time constants

C# provides const and readonly type variables, where variables declared with const are validated at compile time and readonly type variables are validated at runtime.

So, it is recommended to use Runtime constants, which can be set during the initialization time. Runtime constants can be initialized in the constructor of a class.

public const string compileTimeConstant = "abc" ;
public readonly string runTimeConstant = "def" ;

Type casting

It is advisable to follow implicit type casting over explicit one as the latter would throw an error if there is any mismatch.

In order to achieve implicit type casting, 'is' and 'as' operators can be used. 'Is' can be used to check whether the object is of the required type and 'as' to convert the object to a specific type.

if (child is Student)

{

   studentData = child as Student;

}

Implementation of try, catch and finally block

If a block of code that is written for executing a logic is prone to throw errors, it is recommended to enclose the code under the try and catch block.

Once an exception occurs, the control of the code will immediately go to the catch block, and the code written inside it will be executed.

Similarly, in case there is a need to mandatorily close any object in the event of exception or success, then finally block will be executed.

Conclusion

The above are some of the best practices that a developer can follow while writing C# code. As a developer, always maintain a clean code that is easy to understand for other developers even if they have never worked in that piece of code.

Latest