C# language provides many features and null-coalescing operator(??) is one of them. It’s a great operator to check whether object is null and if it is null then it will provide a default value. I have seen most of the people are not using while it’s a great feature. So I decided to write a blog about this.
You can find more information about null-coalescing operator from the below link.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
In below example we are checking nullable integer value whether its having value or not. First we are going to simple check with if else and then we are going to check same with null-coalescing operator.
Out put of both code will be same like following.
That’s it. Hope you like. Stay tuned more..
You can find more information about null-coalescing operator from the below link.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
Example:
using System; namespace ConsoleApplication3 { class Program { static void Main() { Console.WriteLine(Number); Number = 1; Console.WriteLine(Number); } public static int? _number; public static int? Number { get { if (_number.HasValue) { return _number; } else return 0; } set { _number = value; } } } }Here in the number property I have used the if-else loop to check whether number has value or not. We can simply use null-coalescing operator to check whether it has value not like it.
using System; namespace ConsoleApplication3 { class Program { static void Main() { Console.WriteLine(Number); Number = 1; Console.WriteLine(Number); } public static int? _number; public static int? Number { get { return _number ?? 0; } set { _number = value; } } } }
Out put of both code will be same like following.
That’s it. Hope you like. Stay tuned more..
You're right. After so many years programming in C#, I never use this operator even though it's a pretty common scenario. Let's try to change this.
ReplyDeleteThanks for kind word Jan. I am glad that you found its usefull
ReplyDeleteBTW, I guess you'll get it interesting
ReplyDeletehttp://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad
@twitter-172771853:disqus - Thanks for sharing.. It's really good
ReplyDeleteI agree, I have been using this operator for years and every time I get my code reviewed by someone who hasn't coded with me before raises this as an unknown or non standard operator. Lets change that and get people using the whole of the language and not just the subset that they are comfortable with!
ReplyDeletegood thing u described :) (Thanks)
ReplyDeleteyes I Agree its one of the most unappreciated operator over there!!. So we need to find this kind of features and ask people to use it
ReplyDeletethanks Aryan!!
ReplyDelete