web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / DynamicsDevPro / C# - Null conditional opera...

C# - Null conditional operator - Null check with question mark to handle null reference exception

ram r Profile Picture ram r
Hello All,

Its good to meet you with yet another exciting tip and this time its around C#. With C# 6.0 there are many handy features introduced when it comes to day to day development.

One such feature is  Null conditional operator. ?

Personally during c# development, I always felt that in C# we lack better null condition handlers and I had to develop my own extensions to handle the same. But the situation is upside down now and I am loving this new null conditional operator.

Lets go through a quick example with code snippet

Consider the following function where we are trying to replace a value in a string, here we handle null in a conventional way


        private string StringReplaceTest(string input)
{
if (input == null) return null;

return input.Replace("1", "2");
}

With the latest version, we got our handy way to handle the null's and below is the updated code,


        private string StringReplaceTest(string input)
{
return input?.Replace("1", "2");
}

Hope this helps.

This was originally posted here.

Comments

*This post is locked for comments