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.
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 the line
userName = null;
- string userName = "Banketeshvar Narayan";
-
- 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 statement in Immediate window which is as follows:
I have explained it in more details.
Must visit the above link it has more explanation.
756