September 26, 2008

? and ?? feature in C#

Filed under: C# 3.0 — @ 1:47 pm

In C# 3.0 there is a new feature assign and check the null values that lot of people doesn’t know it even exists. Well I didn’t know till couple of months ago. Even though I knew, there were couple of good circumstances I could have used it but never used it. So yesterday I decided to look at the code and see if I can save some typing by using this operators.

Lets jump into an example and look at the operator in action. I like examples more than theory so here it goes…

? is currently used as a trinary operator as we all know. Good example would be

string resturnResult = (value == null)?””:value;

in the previous statement, we are first checking to see if the value is null then assign an empty string to the returnResult else just assign the value in the value variable.

Now the use of ?? operator. The same statement we look at before would be

string returnResult = value ?? “”;

It does the same thing as the earlier statement we look at.  ?? operator will check and see if the value string is null and if it is null then it will assign the value to its right, else assign the value. Isn’t it elegant? I like this code better than the earlier one. We can argue about readability but once you start using it you will learn to read it as well.

Now going back to one other operator ‘?’ Currently it is used in the trinary operator, now it is a new face as well. Something like the following

int? age;

This basically says, the integer variable age could take null value. Why would someone want to do that, to be honest I haven’t used it. So in my limited knowledge on this subject, I could see the use in database side. You might run a stored proc and get user information from table and assign values to these variable which could take null values. If some rows doesn’t have age value set in the columns, that could come as null. So when the value is retrieved and it could be assigned to age variable without throwing an exception. Even though that is the intend, I haven’t sold on this idea yet. So if you any of you have used this operator, please drop me a note.

Thanks and happy coding…

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress