Click here to Skip to main content
Click here to Skip to main content

The ?? operator

By , 4 Sep 2012
 

Introduction

Operator is introduced with Nullable datatype inclusion in .NET Framework operator ?? can also be referred in a word like 'In case of null, pick value from another'

Scenario

Suppose you're assigning a value to Nullable bool like:
 
bool? b = null;
At the time of checking value, it will give you an error like:
if(b) //Error CS0266.
{
 
}
So it's always preferable using ?? to prevent error like
if(b ?? false)
{
}
It defines that, in case b is null, pick the value false.
?? can be also used in multiple choice of value like:
bool ? a = null
bool ? b = null
bool ? c = true
 
a = b ?? c ?? false;
 
That will check b first, If b is undefined or null, then it will move further to check for c if that's also having null then it will set false to a.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Hiren solanki
Software Developer
India India
Member
He is a Smart IT devloper with Few years of Expeariance But having Great command on ASP.net,C#,SQL Query,SSRS,Crystal Reports
 
Apart from that He Loves multimedia work too, Master of Adobe photoshop, Illustrator, CSS , HTML and all things.
 
He is Currently working in Microsoft Dynamics CRM and Having Nice Expearince with CRM. CRM Rocks!!!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionSome revisions?memberYusuf Uzun6 Sep '12 - 12:30 
if a datatype defined with nullable, you can also use its properties such as HasValue and Value. Something like this:
int? nullableInt = 10;
if ( nullableInt.HasVale)
{
DoSomethingWhatYouWant(nullableInt.Value);
}
 
Using this not a proper way in my opinion:
if(b ?? false)
{
}
 

So the tip's subject is good but context is little bit poor.
But for beginners still usable...
GeneralRe: Some revisions?memberHiren solanki6 Sep '12 - 20:33 
Hi Yusuf,
 
Using HasValue can be a good option instead of null-coalescing operator.
 
But Again use of both depends on the situation.
 
For instance, Say if you want to assign a some default value while object have null value. It can be useful.
 
HasValue Can no doubt be useful as you said and it's perfect to use for example you provided.
 
Thanks for your comments.
-Signature is under construction-

GeneralMy vote of 5memberWolfieH6 Sep '12 - 11:19 
My vote of 5 is to cancel out the vote of 1 from the person that clearly didn't read the article.
 
Good tip - short and straight to the point. Well done.
GeneralRe: My vote of 5memberHiren solanki6 Sep '12 - 20:34 
Thanks WolfieH.
 
Appreciating your help.
-Signature is under construction-

GeneralMy vote of 1 [modified]memberSavalia Manoj M5 Sep '12 - 20:49 
Not work in value assign.

modified 7 Sep '12 - 2:59.

GeneralRe: My vote of 1memberHiren solanki5 Sep '12 - 21:36 
Can you please brief your code what all are you doing in assign ?
-Signature is under construction-

GeneralRe: My vote of 1memberSavalia Manoj M6 Sep '12 - 1:44 
Hi Hiren,
I am try to this,
   int? oval;
   oval = 10;
   int val = oval;//this line gives error. 

GeneralRe: My vote of 1memberHiren solanki6 Sep '12 - 2:56 
Hi Manoj,
 
You are casting from nullable type to non-nullable type.
 
Either way you aren't using ?? operator. and casted a blind 1 vote on my TIP.
 
Anyway, Here comes my TIP useful to you, Try with this.
 
   int? oval;
   oval = 10;
   int val = oval ?? 0;
-Signature is under construction-

GeneralRe: My vote of 1memberSavalia Manoj M6 Sep '12 - 20:17 
Thanks Hiren solanki,
it's working now.
GeneralRe: My vote of 1memberHiren solanki6 Sep '12 - 20:29 
In that case I would request you to revise your vote. Smile | :)
-Signature is under construction-

GeneralRe: My vote of 1memberSavalia Manoj M6 Sep '12 - 20:58 
Hi Hiren solanki, I already revise my vote.
GeneralMy vote of 1memberafaz4 Sep '12 - 22:52 
Poor content
GeneralRe: My vote of 1memberHiren solanki4 Sep '12 - 23:00 
Content of your reply is too poor to justify my TIP.
 
I would like to know your suggestion on what additionally I can write on ?? operator, Doesn't this enough to get you understand the whole idea behind ?? operator ? or you want to go beyond the code and want to know the operation takes place at compiler, and assembly level ?
 
BTW it's a TIP not an article.
-Signature is under construction-

GeneralRe: My vote of 1memberAndreas Gieriet5 Sep '12 - 3:52 
The vote of 1 is a bit too low, but I somehow understand why a lower vote is given.
 
You not even give the proper name to that operator: it's the Null Coalescing (Wikipedia)[^] operator.
 
IMHO, the given example is kind of poorly chosen: nullable value types are useful for database type map - otherwise I consider them as a code smell.
 
A more realistic scenario is in connection with reference types and especially with Enumerable<T> (e.g. linq queries):
 
Record GetFirstOrSentryRecord(Func<MyRecord, bool> predicate)
{
    var query = from record in table where record=>predicate(record) select record;
    return query.FirstOrDefault() ?? MyRecord.SomeSentryRecord;
}
Or with defensive programming, at locations where you want no null values, e.g.:
HandleError(..., context ?? "no context");
Etc.
 
Rule:
 
The ?? operator is everywhere usable where you have an instance of a reference type (including nullable value types) that may evaluate to null.
 

expandedwith ternary operatorwith null coalescing operator
result = item;
if (result == null)
{
    result = other;
}
result = item != null
       ? item
       : other;
 

result = item
         ?? other;
 

 
 
Finally, a good tip provides references to say where to go from here, e.g.
 
Cheers
Andi
GeneralRe: My vote of 1memberHiren solanki5 Sep '12 - 3:58 
Thanks Andi for your valuable input.
 
I created this TIP 1.5 year ago in CP. Today After 1.5 year I just updated a single type from 'boll' to 'bool'.
 
I think my typo modification is worth at this time getting good amount of knowledge from you.
 
Thanks.
-Signature is under construction-

GeneralRe: My vote of 1memberAndreas Gieriet5 Sep '12 - 5:12 
You are welcome.
Cheers
Andi
GeneralMy vote of 4memberAndreas Gieriet18 Apr '12 - 23:18 
I have a certain hesitation to use nullable basic value types. I think a more realistic szanario of the ?? operator is with Linq queries, e.g., ...FirstOrDefault() ?? myDefault.
And in the same go, the default(T) operator could have been mentioned. That's another construct that is relatively little known. The default(T) comes into play with that particular Linq function FirstOrDefault(...).
Cheers
Andi
GeneralReason for my vote of 5 Good to remind people about (new) la...memberjohannesnestler21 Feb '12 - 3:39 
Reason for my vote of 5
Good to remind people about (new) languages features.
GeneralReason for my vote of 5 nice onemembernikhi _singh9 Feb '12 - 1:45 
Reason for my vote of 5
nice one
GeneralReason for my vote of 5 Simple tip; Doesn't matter if I coul...memberJustin Helsley6 Oct '11 - 9:23 
Reason for my vote of 5
Simple tip; Doesn't matter if I could have looked it up on MSDN...
GeneralReason for my vote of 5 Completly forgot about this operator...membersucram16 Jan '11 - 22:45 
Reason for my vote of 5
Completly forgot about this operator. Thanks for reminding me I will definetly uses so as not to forget it again.
GeneralAre you gonna now describe other operators as well? :)memberjszczur3 Jan '11 - 11:57 
Are you gonna now describe other operators as well? Smile | :)
GeneralThank you bob.memberHiren Solanki28 Dec '10 - 18:14 
Thank you bob.
GeneralReason for my vote of 5 Very usefull in database datamemberBob Baeck28 Dec '10 - 9:09 
Reason for my vote of 5
Very usefull in database data
General@SAKryukov : I am sorry,I didn't get what you're trying to c...memberHiren Solanki27 Dec '10 - 20:30 
@SAKryukov : I am sorry,I didn't get what you're trying to convey, please elucidate it.
General@JH64 : Thanks. Yes that's some excessive white space while ...memberHiren Solanki27 Dec '10 - 20:28 
@JH64 : Thanks.
Yes that's some excessive white space while pasting code.
GeneralHiren, unfortunately, adding "Also, it is not limited to nul...mvpSAKryukov27 Dec '10 - 20:28 
Hiren, unfortunately, adding "Also, it is not limited to nullable types" (important) instead of improving the Tip text is again not in your favor.
General@brad : I haven't said it's limited to NULL only I said it w...memberHiren Solanki27 Dec '10 - 20:27 
@brad : I haven't said it's limited to NULL only I said it was more useful while nullable datatype is included in .net framework. Also I've simplified ?? in word 'in place of null choose among nonNULL alternatives.
GeneralReason for my vote of 4 Nice. I will try to use ??. I think...memberJH6427 Dec '10 - 7:16 
Reason for my vote of 4
Nice. I will try to use ??.
 
I think this is a typo "boll ? c = true" and what you did mean is "bool ? c = true".
GeneralIt is called the null-coalescing (or coalesce) operator. It...memberbrad.ford@cudl.com27 Dec '10 - 6:35 
It is called the null-coalescing (or coalesce) operator. It is good to become familiar with the terminology.
 
Also, it is not limited to nullable types, as in:
 
var client = default(Client); // is == null, but has the type Client
var myClient = client ?? new Client();
 
http://msdn.microsoft.com/en-us/library/ms173224.aspx
General@SledgeHammer01 : It was just reference from MSDN, Not copy ...memberHiren Solanki23 Dec '10 - 18:33 
@SledgeHammer01 : It was just reference from MSDN, Not copy and paste.
Tell me there's a single line which I've copied.
 
Thanks.
SuggestionRe: @SledgeHammer01 : It was just reference from MSDN, Not copy ...memberClifford Nelson7 Sep '12 - 14:29 
You should reply to the comment by SledgeHammer01, not do a general reply. Open up his comment, and there will be a reply on the comment.
GeneralRe: @SledgeHammer01 : It was just reference from MSDN, Not copy ...memberHiren solanki7 Sep '12 - 18:50 
I know, I have passed quite a lot time now in CP.
 
In Earlier time, Comments/Replys to TIP were not getting written in thread. This is the migrated data from those TIP so not displaying well threaded.
 
TIP is so old.
-Signature is under construction-

GeneralReason for my vote of 5 nice tipmemberSChristmas23 Dec '10 - 5:32 
Reason for my vote of 5
nice tip
GeneralReason for my vote of 2 copy and paste from MSDNmemberSledgeHammer0123 Dec '10 - 5:11 
Reason for my vote of 2
copy and paste from MSDN

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 5 Sep 2012
Article Copyright 2010 by Hiren solanki
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid