There’s an old saying, “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” Fixing and improving code written months ago is difficult, especially if someone else needs to do it. Here are a few C# tips that will make your code more elegant and readable.

Tip 1. Conditional operator ?:

The Conditional operator provides a fast and simple way of writing if-else statements:

condition ? first_expression : second_expression;

This means: If the condition is true, return the first expression, and if the condition is false, return the second expression.

In the following example, we have an if else statement that verifies if the variable number is greater than 5 and depending on the result, displays a certain message.

int number = 6;
string message = string.Empty;

if (number > 5)
     message = $"{number} is greater then 5!";
     message = $"{number} is even or less then 5!";

This code is pretty simple, but it can be written in even fewer lines and be equally understandable:

int number = 6;
string message = string.Empty;

message = number > 5 ? $"{number} is greater then 5!" : $"{number} is even or less then 5!";

Tip 2. Null coalescing operator ??

The null coalescing operator returns left-hand operand if the operand is not null, and if it is, the right-hand operand is returned. Using this operator, we can avoid Null Reference Exception, which is thrown when we try to use something that is null. Here’s an example:

string variable = string.Empty;
string message = string.Empty;
variable = "Not null";
message = variable ?? "Default message if variable is null"; 

variable = null;
message = variable ?? "Default message if variable is null";

Null Coalescing Operator

Tip 3. Null conditional operator ?.

The null conditional is a form of a member access operator. With a null conditional operator, the expression A?.B evaluates to B if the left operand (A) is non-null; otherwise, it evaluates to null.

Person person = new Person
    Name = "Joe",
    Shoes = null

int? numberOfShoes = person.Shoes?.Count;

This example shows how to check if person has shoes by using a null conditional operator, so we don’t need to check for nullability of this property.

Using tip no. 2, we can write:

int numberOfShoes = person.Shoes?.Count ?? 0;

If the person doesn’t have shoes, the numberOfShoes will equals 0.

Tip 4. Casting

If we try to cast two objects that cannot be cast, we will get System.InvalidCastException, and the program will crash, as in the example shown below:

object number = 6;
string text = (string)number;

However, if we try to do cast with as operator instead of the exception, we will get null:

object number = 6;
string text = number as a string;

Moreover, using a simple check if the variable text is null, we can save time for writing try-catch block and handling exception.

Tip 5. StringBuilder for large amounts of text

If you have a situation where you need to append many strings - especially if they are large - use StringBuilder instead of String. String is an immutable type which means each time you change its value, you create a new String object. Because of that, your application can become very slow when you need to perform this operation many times.

Stopwatch stopwatch = new Stopwatch();
int loopNumber = 10000;
string text = "text";

string stringText = string.Empty;

for (int i = 0; i < loopNumber; i++)
    stringText += text;
Console.WriteLine($"String took {stopwatch.ElapsedMilliseconds} miliseconds.");

StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < loopNumber; i++)
Console.WriteLine($"String Builder took {stopwatch.ElapsedMilliseconds} miliseconds.");

StringBuilder vs String

Those are 5 simple tips which can make coding faster and more understandable. Read more on this topic in the official Microsoft documentation.

More articles

Your opinion matters!

comments powered by Disqus