Tuesday, January 8, 2008

Lesser known elements of C#: Coalescing

Unless you read through all 800 or so pages of the C# specification, and honestly I've had more fun bashing my head against a bowl of weetabix then you could be forgiven for missing out of some of the lesser known elements of the language. One of which is the coalescing operator. You may have come across the term "Coalesce" in SQL and the meaning is almost identical in C#. Let's look at an example:


string YourName = SomeString ?? "Joe Public";


So what does this means? Well if the string "SomeString" is null then the string "YourName" will be set to "Joe Public". If it's not null then the string "YourName" will be set to the value of "SomeString". So the element before the ?? operator will be used unless it's null, in which case the element after the ?? operator is used. In essence this is similar to the ISNULL feature of T-SQL or the COALESCE feature of SQL. It's not something that'll change your life for the better but it's a great party trick because, in my own experience, a lot of c# programmers haven't come across it. So go nuts, impress your friends :)

0 comments: