Any examples of '?' and '??" in c# [Resolved]

Posted by Jitendrasoft09 under C# on 7/1/2017 | Points: 10 | Views : 149 | Status : [Member] [MVP] | Replies : 2
what is the exact difference between '?' and '??' symbol in c#.

Jitendra Kumar
If my post helps you, plz mark as an answer.



Responses

Posted by: A2H on: 7/1/2017 [Member] [MVP] Silver | Points: 50

Up
0
Down

Resolved
?? is null-coalescing operator. This operator will return the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
Example

int? x = null;

// Below code will assign value of x to variable Y if x is NOT null
// However if x = null, variable Y is set to -1.

int y = x ?? -1;




Thanks,
A2H
My Blog

Jitendrasoft09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: A2H on: 7/1/2017 [Member] [MVP] Silver | Points: 25

Up
0
Down
? is Null conditional operator which is introduced with C# 6.0. This will first check for the null and then do the operation based on that.
See the below example
string firstname = null;
//Check if Firstname is null or not
if(firstname != null)
{
string res = firstname.Substring(0, 4);
}


Earlier we use to handle null conditions like above other wise code will throw null reference exception

With new null conditional operator we can change the code like below
string firstname = null;
//Handle the null case using the operator(?) this wont throw null reference exception
string res = firstname?.Substring(0, 4);


Reference Url
https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

Thanks,
A2H
My Blog

Jitendrasoft09, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response