Long time I asked myself, for what the heck I could use the ?? operator. Last days I found the perfect scenario for using this operator.
Think about accessing your application config file using the configuration manager. This could look like:
string value = ConfigurationManager.AppSettings["AppKey"];
if (value == null)
value = "DefaultValue";
If you want to do it a little bit more elegant, you could use this code:
string value = ConfigurationManager.AppSettings["AppKey"];
value = (value != null) ? value : "DefaultValue";
Or you say:
string value = ConfigurationManager.AppSettings["AppKey"] ?? "DefaultValue";
I think, that’s Impressive! If you have some other use cases for this operator I would like to know them.
Cheers
- Gerhard
November 11, 2007 at 12:33 pm
It’s its, not it’s
November 11, 2007 at 1:08 pm
Hi,
recently I also wrote several articles about the null coalescing operator: http://blog.krisvandermast.com/SearchView.aspx?q=%22null%20coalescing%20operator%22.
Since I found out about the existence of this incredible usefull operator I used on all possible occasions. Too bad VB.NET doesn’t support an equivalent of it.
Grz, Kris.
November 11, 2007 at 4:16 pm
In VB.net you can kinda fake it with a generic method, but the C# operator is just so much more elegant.
November 12, 2007 at 5:19 pm
I couldn’t understand some parts of this article nnial 2007 – salvatore iaconesi – del.icio.us poetry, but I guess I just need to check some more resources regarding this, because it sounds interesting.
November 12, 2007 at 7:01 pm
This was my absolute favorite change when moving from VB to C#
February 15, 2008 at 6:59 pm
great! I wa using something stupid like this:
int val;
int.TryParse(ds.Tables[0].ds.Tables[1].Rows[0]["PAY_MONTH"].ToString().Trim(), out val);
payMonth = val;
and now:
payMonth = ds.Tables[1].Rows[0]["MES124"].ToString().Trim() ?? 0;
Thanks Gerhard, 3rd time I found something useful here, keep the good coding…
July 9, 2008 at 5:25 pm
That’s pretty cool – I’ve never really understood the use of the ? and ?? operators. Between that and LINQ – I can probably clean up my C# code
August 21, 2008 at 1:30 pm
You can also string ?? operators together which makes it even more useful sometimes, e.g.:
string value = ConfigurationManager.AppSettings["AppKey"] ?? ConfigurationManager.AppSettings["UserKey"] ?? “DefaultValue”;
This allows you to prioritise assignment of values and use the first non-null or the default if all are null.