C# Null Conditional Operator

This article will teach you about the Null Conditional Operator?. in C#.

C#  introduces the Null Conditional Operator. Instead of throwing an exception, it will return null if the left-hand side expression is evaluated to null (NullReferenceException).

If the left-hand side expression evaluates to a non-null value, it will be considered normal .(dot) operator and may return null because its return type is always a nullable type, which means that it is wrapped inside a NullableT> for structs and primitive types.

var id = Employee.GetEmployeeId()?.Value; 
var employeeId= Employee.GetEmployeeId()?.IntegerValue;

This is useful when firing events; ordinarily, we invoke an event within the if condition by null checking, which introduces a race issue. We may remedy this with the Null Conditional Operator, as seen below.

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

Here’s an example 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 = "Abc", LastName = "Test" , Address = "15,abcd"
            };
            GetEmpDetails(emp);
            Console.ReadKey();
        }
        public static void GetEmpDetails(Employee emp) {
            Console.WriteLine("Employee Details:");
            Console.WriteLine(emp?.FirstName); 
            Console.WriteLine(emp?.LastName); 
            Console.WriteLine(emp?.Address); 
        }
    }
    public class Employee {
        public int EmpId {
            get;
            set;
        }
        public string FirstName {
            get;
            set;
        }
        public string LastName {
            get;
            set;
        }
        public string Address {
            get;
            set;
        }
    }
}

 

Submit a Comment

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

Subscribe

Select Categories