Null Propagation Operator in C# 6.0
Every developer who writes C# code should have encountered NullReference exception or Object Reference not set to an instance of an object error at least once. This error normally happens when you try to invoke a member of an object without performing a null check on the object. For example the following code will produce a compiler error
So normally to solve this issue we will introduce a conditional checking before invoking the property as shown below
C# 6.0 introduces a new operator called null propagation operator or ?. operator that helps to short circuit this verbose approach. So the above code can be rewritten as shown below
If you look at the Console.WriteLine method in the code, you can see that I am trying to invoke the Name property on a null object. Since I have used the null propagation operator before the accessing the property, compiler will first check for null and it will invoke the property if and only if the object is non nullable. If the null check returns successful then it will return a null .
You can read more about it in the links given below
http://davefancher.com/2014/08/14/c-6-0-null-propagation-operator/
http://www.c-sharpcorner.com/UploadFile/66489a/null-propagation-operator-in-C-Sharp-6-0/
No Comments
Connecting Azure Blob Storage account using Managed Identity
Posted 12/9/2022Securing Azure KeyVault connections using Managed Identity
Posted 11/26/2022Manage application settings with Azure KeyVault
Posted 11/9/2022Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020