Sometimes developers get the following exception
“Object reference not set to an instance of an object”. Whenever we got such type of exception our mouth fell open but in C# 6 we can handle it easily using NULL Conditional Operator. So we can handle “System.NullReferenceException” using this operator. I am going to explain it with a very simple example where I am handling NullReferenceException for string datatype.
What is a Null-Conditional operator?
Before C# 6
string name = null;
int length = name.Length;
It will throw the following error.

In C# 6.0
using static System.Console;
namespace BNarayan.NullConditionalOperator
{
class Program
{
static void Main(string[] args)
{
string userName = "Banketeshvar Narayan";
userName = null;
if ((userName?.Length??0)>20)
{
WriteLine("UserName can not be more than 20 charcter long.");
}
else
{
WriteLine("UserName length is: {0}", userName?.Length??0);
}
}
}
}
Output

If I comment on the line userName = null;
string userName = "Banketeshvar Narayan";
//userName = null;
if ((userName ? .Length ? ? 0) > 20)
{
WriteLine("UserName can not be more than 20 charcter long.");
}
else
{
WriteLine("UserName length is: {0}", userName ? .Length ? ? 0);
}
Output

I have tested the output for some statements in the Immediate window which is as follows.

I have explained it in more details.
Must visit the above link it has more explanation.

Banketeshvar NarayanPosted Nov 18, 2015, 10:49 AM
Yaduveer Saini Thank you
Yaduveer SainiPosted Nov 18, 2015, 9:27 AM
Good One Thanks for Sharing
Banketeshvar NarayanPosted Nov 16, 2015, 10:13 AM
Thanks Anish
Banketeshvar NarayanPosted Nov 16, 2015, 10:11 AM
Thanks Aishwarya
Aishwarya DPosted Nov 16, 2015, 7:08 AM
Thanks for sharing
Anish AnsariPosted Nov 16, 2015, 12:41 AM
nice onne
Banketeshvar NarayanPosted Nov 13, 2015, 3:13 AM
Thanks & Welcome Suman
Suman VermaPosted Nov 13, 2015, 2:48 AM
Thanks for sharing
Banketeshvar NarayanPosted Nov 11, 2015, 8:20 AM
Thanks Santhakumar
Santhakumar MunuswamyPosted Nov 11, 2015, 7:09 AM
Good one
Banketeshvar NarayanPosted Nov 9, 2015, 1:41 PM
Hi all, I have just explained this topic in more details. you can find more explanation here http://forums.asp.net/post/5989234.aspx
Banketeshvar NarayanPosted Nov 9, 2015, 12:50 AM
Thanks every one for giving your precious time to read this and appreciate me.
Banketeshvar NarayanPosted Nov 9, 2015, 12:47 AM
Thanks Humayun
Humayun Kabir MamunPosted Nov 9, 2015, 12:24 AM
Nice...
Banketeshvar NarayanPosted Nov 8, 2015, 11:11 PM
thnx Harshad
Harshad PansuriyaPosted Nov 8, 2015, 11:06 PM
Nice one
Banketeshvar NarayanPosted Nov 8, 2015, 8:50 AM
thanks Rajeesh
Banketeshvar NarayanPosted Nov 8, 2015, 8:50 AM
thnx Gowtham
Rajeesh MenothPosted Nov 8, 2015, 8:31 AM
Good Start!
Gowtham KPosted Nov 8, 2015, 7:00 AM
Good One
Banketeshvar NarayanPosted Nov 7, 2015, 11:46 PM
Thanks Mukesh
Mukesh KumarPosted Nov 7, 2015, 10:56 PM
Good job.....Welcome to tech professional community.