C# Performance Improvement Tips – By using ? operator

The ? operator plays very important role in C# with respect to code performance. The ? operator is most commonly known as conditional operator in C#. In this article I will explain with code example ans see how we can make use of ? operator in order to run our C# code faster.

C# Performance Improvement Tips – Use of ? operator

The ? operator can be used in various reason in C#. Below are the few basic code constructs explained with example.

  • The ? used as conditional operator
  • The ?? used as Null coalescing operator
  • The ? used as Null conditional operator

1. Conditional Operator that replace If – Else condition:

The ? operator can be used to evaluate expression conditionally. This replace the traditional way of using If-Else condition. The primary advantage using ? operator keep the code simple and compact. Here is the syntax.

Recommended:   Visual Studio C# Code Snippets Overview

AssignmentVarible = condition ? first_expression : second_expression;

This means that if the condition is true, then first_expression will be evaluated. Otherwise second_expression will be evaluated.

In the below example, we will first see how the traditional If_Else condition looks.

Here is the code that demonstrate ‘?’ is used as conditional operator.

2. Null coalescing operator ??

The ? can be used as Null coalescing operator that returns left hand operand if the operand is not null. Otherwise, the right hand operand is returned. The primary purpose of this operator is to avoid NullReferenceException.

3. Null conditional operator ?

This null conditional operator is kind of member access operator that evaluates the object for null before accessing its members with out explicit null value check. The syntax is as below.

Recommended:   Browse Code Samples - for Microsoft Platform Developers

result = ClassObject?.ClassMemberVariable;

In the above syntax, ClassMemberVariable is evaluated only if ClassObject is initialized or not null. Otherwise, null is returned.

In this example, if we don’t need to check for null-ability of the Address object explicitly. The expression will return the door number only if the Address object is not null.
Please note
above example showing compiler error as this code will work only with c# version 8.

Share this:

We will be happy to hear your thoughts

Leave a reply