Cool stuff: C# ?? null operator

14 Jul

I’ve been working more with C# for a while. It’s hard to admit (Microsoft stuff, you know) but I’m starting to like it. So I will do some posting about some cool stuff that I find while programming, it will maybe help you out.

The ?? operator let’s you create cleaner and faster code, this is how it would be done without the ?? operator

Object aNullObject = null;
Object aNotNullObject = new Object();
Object ResultingObject = 
        aNullObject == null ? aNotNullObject : aNullObject;
bool result = ResultingObject == aNotNullObject;
//result is true

Now with the ?? operator:

Object aNullObject = null;
Object aNotNullObject = new Object();
Object ResultingObject = aNullObject ?? aNotNullObject;
bool result = ResultingObject == aNotNullObject;
//result is true

Cleaner and easier! If you want to read more about it there is a nice post on Scott Guthrie’s Blog