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 a code example and see how we can make use of ? operator in order to improve the code execution speed.
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 replaces the traditional way of using If-Else condition. The primary advantage using ? operators keep the code simple and compact. Here is the syntax.
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 a kind of member access operator that evaluates the object for null before accessing its members without an explicit null value check. The syntax is as below.
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.
– Article ends here –