Categories : Development
Author : Date : Nov 23, 2021
This post will help you speed up your C# code and provide many tricks that every professional developer must know.
Look at the code snippet below
In this method we have many lines of code and we need to read all the code to find the last line that throws an exception if the argument is null. Instead, we can validate the input first. This tells the viewer of the code how a given method should be used.
The below code is rewritten with the reverse order of if and else statements.
You can now quickly tell what is the valid argument for this method
Let’s continue with the same previous example. If an employee is null we throw an exception and code does not continue to execute. So there is no need for an else block. Having an else block here only increases the indentation of the code. Here is a better way to write this code.
One of the features added from C# 6 onward is a way to initialize properties directly like fields. We usually create constructors to initial properties like below.
Instead of the constructor used above we can directly initialize the property as shown below.
Many times we would have encountered the following type of coding for checking an object for null before accessing one of its members.
From C# 6 onwards we have a null-conditional operator (?) that evaluates null. If the object is null then the value null will be returned.
In the above example there are two null-conditional operators, one checks null in the employee object and another checks null in the address object present inside the employee. If any one is null then addressID will be set to null.
Continuing from above example, in case we do not want null value to be returned and want addressId to be an integer with default value ‘0’ when employee or address is null. We can use the null-coallescing operator (??) as shown below.
We can often encounter methods having single line return statement like below
Instead of above we can rewrite using expression bodied members, thus it reduces line indentation.