Friday, 19 May 2017

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

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.

No comments:

Post a Comment

Contact Form


Email *

Message *