??: The New C# Operator
posted on 12/09/05 at 09:24:31 pm by Joel Ross
I hadn't seen this in any of the C# 2.0 feature lists, but Fritz Onion brings this little gem to light for me. There's a new operator: ?? It's a lot like the old inline if statement:
(Test) ? [True statement] : [False statement];
Well, it's different than this (less powerful), but most of the time, here's what I use the ?: operator for:
(myString == null) ? "" : myString;
Basically, it's an easy way to ensure that nulls aren't getting passed around. Better yet, I've found it very useful with databases - when a datetime field supports nulls, but you can't have a null DateTime in .NET, you can check for a null value, and then assign it a default value, like DateTime.MinValue.
Well, now you can shorten this type of code to this:
(myString ?? "");
That's it! I'm sure I'll be using this now that I know about it.
Categories: Development