post-ad

Conditional Operator For Null In C#

You will discover more about the C# Null Conditional Operator in this blog.

In C# 6.0, the Null Conditional Operator?. is introduced. If the left-hand side expression is evaluated as null, it will return null rather than raising an exception (NullReferenceException). The return type of the left-hand side expression is always a nullable type, which implies that for a struct or primitive type, it is wrapped into a NullableT>. If the left-hand side expression evaluates to a non-null value, it will be handled as a standard.(dot) operator and may return null.

var id = Emp.GetEmpId()?.Value; // This will returns null if GetEmpId() returns null.
var empId= Emp.GetEmpId()?.IntegerValue; // Here empId will be of type Nullable<int>, that is int?

This is useful for firing events since otherwise when we activate an event inside of an if statement by null checking, a race situation is introduced. Null Conditional Operator allows us to fix as follows:

event EventHandler<string> RaiseAnEvent;
RaiseAnEvent?. Invoke("Event has raised");

Here is an illustration of how to use a null conditional operator:

using System;
namespace NullConditionalOperator {
    class Program {
        static void Main(string[] args) {
            Employee emp = null;
            GetEmpDetails(emp);
            emp = new Employee() {
                FirstName = "Rajanikant", LastName = "Hawaldar"
            };
            GetEmpDetails(emp);
            Console.ReadKey();
        }
        public static void GetEmpDetails(Employee emp) {
            Console.WriteLine("Employee Details:");
            Console.WriteLine(emp?.FirstName); //use ?. operator
            Console.WriteLine(emp?.LastName); // use ?. operator
        }
    }
    public class Employee {
        public int EmpId {
            get;
            set;
        }
        public string FirstName {
            get;
            set;
        }
        public string LastName {
            get;
            set;
        }
    }
}

In this blog post, we reviewed the Null Conditional Operator using an example.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories

page-ad