NULL conditional operator or NULL propagation operator was introduced with C# 6.0 and you will find dozens of blogs and articles on NULL conditional operator. I have also written some articles on it and following is a link for the same but I have noticed that very few people are using all the benefits of NULL conditional operator.
NULL Conditional Operator In C# 6.0
In this blog, I am going to present those hidden gems for you.
There are 2 syntaxes for NULL conditional operator, which are given below.
- NULL conditional operator for member access (?.)
- NULL conditional operator for index based access (?[)
So the first syntax “?.” is being used very popularly but the second syntax “?[” is used by very few people. But I am going to cover all those in this blog.
NULL conditional operator for member access (?.)
Have a look at the code snippet given below.
- static void Main(string[] args)
-
- {
-
- string name = null;
-
- int length = name.Length;
-
- }
The preceding code snippet will throw an exception NullReferenceException.
If I use the NULL conditional operator (?.), then the preceding code snippet can be written as given below.
- static void Main(string[] args)
-
- {
-
- string name = null;
-
- int? length = name?.Length;
-
- }
It will run successfully without throwing any exception.
NULL conditional operator for member access (?.) with null-coalescing operator (??)
if you do not want to make the length variable as Nullable int type, then you can use null-coalescing operator (??) with “?.” Follow the code snippet given below for the same.
- static void Main(string[] args)
-
- {
-
- string name = null;
-
- int length = name?.Length ?? 0;
-
- }
More useful example with complete code is given below.
- using static System.Console;
-
- namespace NULLConditionalOperatorExample
-
- {
-
- class Program
-
- {
-
- static void Main(string[] args)
-
- {
-
- Customer cust = new Customer { Id=101};
-
- WriteLine($"Customer id: {cust.Id} & name: {cust.Name??"N/A"}");
-
- WriteLine($"Customer name contains {cust.Name?.Length ??0} character(s)");
-
- }
-
- }
-
- class Customer
-
- {
-
- public int Id { get; set; }
-
- public string Name { get; set; }
-
- }
-
- }
NULL conditional operator for index based access (?[)
Have a look at the code snippet given below.
- static void Main(string[] args)
-
- {
-
- int[] Numbers = { 1, 2, 3, 4, 5 };
-
- Numbers = null;
-
- WriteLine($"5th element is: {Numbers[4]}");
-
- }
The preceeding code snippet will throw an exception NullReferenceException.
If I use the NULL conditional operator (?[), then the preceeding code snippet can be written, as given below.
- static void Main(string[] args)
-
- {
-
- int[] Numbers = { 1, 2, 3, 4, 5 };
-
- Numbers = null;
-
- WriteLine($"5th element is: {Numbers?[4]}");
-
- }
It will run successfully without throwing any exception.
You can also learn about C# 7 by going through the links given below.