Some Cool Coding Tips
I was doing some nighttime programming for fun, and came across a bit of code I had to look up (i.e. search on the web). In C#, I was familiar with ternary operators. I love using them when appropriate. It turns 3 ~ 5 lines of code into one pretty, simple statement.
When I came across a coalescing operator, my head exploded (ok, that may be a bit over-the-top…).
Coalescing operators have a fantastic usage (particularly in C#) with nullable objects.
Example time!
Lets say we’re posting data to a form. The form contains a name (which is an optional field) and birth year (another nullable field).
Assuming we have a “Person” object, that takes a string and integer for a birthdate, we could code that up as follows to handle the null-case of those objects being passed in.
public void doThis(String? name, int? birthyear)
{
Person p = new Person();
// option #1 - if statements
if(name!=null)
p.name=name;
else
p.name = “Bob”;
if(birthyear != null)
p.birthyear = birthyear;
else
p.birthyear = 1902;
// option #2 — ternary operators
p.name = name!=null ? name : “Bob”;
p.birthyear = birthyear != null ? birthyear : 1902;
//option #3 — coalescing operator
p.name = name ?? “Bob”;
p.birthyear = birthyear ?? 1902;
}
How about that for a super quick example? I’m not sure how useful this is, but it seemed like a cool little tidbit of information to come across that I was previously unaware of. Maybe it’s time I start reading up on the changes between C# 3.0, 3.5 and 4.0. If I start doing that, I’ll need to look in the differences between Java 6 and 7 (I have 5 and 6 down pretty well), and don’t get me started on PHP 4 and 5…
Ah well, that’s all. Hope someone on the interwebs finds this useful!