Wednesday, 17 January 2007

I guess I've been under a rock, because I just discovered this operator this evening.  Catching up on some of my unread blogs and read this post on Tests for Null in which mentioned the new coalescing operator (??) in C# 2.0.  How had I never noticed this before.  I could use this almost every day and I'm always one for neatness and compact code so this kind of operator will fit nicely into my toolset.

How does it work?  Well it simply checks if something is null, if not null, returns that something otherwise if null it returns the alternative.  Works very similar to the Coalesce keyword in SQL Server (which I do use often)

ThisClass objClass = aClass ?? new ThisClass();

Which is equivalent to

ThisClass objClass;
if (aClass != null)
   objClass = aClass;
else
   objClass = new ThisClass();

and also;

ThisClass objClass = (aClass != null) ? aClass : new ThisClass();

 

Wednesday, 17 January 2007 22:32:22 (Eastern Standard Time, UTC-05:00) | Comments [0] | .NET#
Search
Archive
Links
Categories
Admin Login
Sign In
Blogroll
Themes
Pick a theme: