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.

  1. static void Main(string[] args)
  2. {
  3. string name = null;
  4. int length = name.Length;
  5. }
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.

  1. static void Main(string[] args)
  2. {
  3. string name = null;
  4. int? length = name?.Length;
  5. }
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.

  1. static void Main(string[] args)
  2. {
  3. string name = null;
  4. int length = name?.Length ?? 0;
  5. }
More useful example with complete code is given below.
  1. using static System.Console;
  2. namespace NULLConditionalOperatorExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Customer cust = new Customer { Id=101};
  9. WriteLine($"Customer id: {cust.Id} & name: {cust.Name??"N/A"}");
  10. WriteLine($"Customer name contains {cust.Name?.Length ??0} character(s)");
  11. }
  12. }
  13. class Customer
  14. {
  15. public int Id { get; set; }
  16. public string Name { get; set; }
  17. }
  18. }

NULL conditional operator for index based access (?[)

Have a look at the code snippet given below.
  1. static void Main(string[] args)
  2. {
  3. int[] Numbers = { 1, 2, 3, 4, 5 };
  4. Numbers = null;
  5. WriteLine($"5th element is: {Numbers[4]}");
  6. }
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.

  1. static void Main(string[] args)
  2. {
  3. int[] Numbers = { 1, 2, 3, 4, 5 };
  4. Numbers = null;
  5. WriteLine($"5th element is: {Numbers?[4]}");
  6. }
It will run successfully without throwing any exception.

You can also learn about C# 7 by going through the links given below.