Sunday, May 12, 2024

Null conditional Operator, Null Coalescing Operator, Null Forgiving Operator in C#

  

Null Conditional Operator (?): Generally used with Object reference variable before accessing any property of that object, it checks that if object is null then it will return null without accessing any property of that object and prevent from object reference exception. for example,

var customerName = objCustomer?.Name ;

Above expression return null if objCustomer is null without accessing Name property of Customer.

Null-Coalescing Operator (??): If applied variable is null then it will return right hand side given value else it will return value of variable. for example,

var customerName=objCustomer?.Name?? "Not Found";

If customer has no value (null) for its name, then above expression will return "Not Found" else name of customer.

Null Forgiving Operator (!): If Nullable enabled in project file means you are using null state analysis feature for framework, which allow you to define reference type either nullable or non- nullable.  If non nullable reference type contains null compiler will generate warning. sometimes we know that this variable is nullable variable, and it has non null value, but compiler still force you to check for null, in this case you can use (!) null forgiving operator to tell that I know it's not null, don't generate warning. 

 Product?[] products = Product.Get(); 

 var productName= products[0]!.Name ;

Note: You can disable null state analysis on specific file by using " #pragma warning disable CS8602.


No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...