Recently I gave a quick talk to the devs at the court house about the
coalesce operator. So why do you care? Well, you probably don’t so
just quit reading right now.

For those of you that are still around the coalesce operator works like

For instance:

hourly_wage * 40 * 52,
commission * num_sales) AS 'Total Salary' FROM wages

Here in T-SQL we can see a simple select statement that will determine a
person’s total salary regardless of if they are on wage, salaried or on
commission since an employee on wage would have a null salary and null
commission but an employee on salary would have a null wage and null

Basically COALESCE uses the first value it finds that doesn’t result in
a null.

So how can this help you?

Does this look familiar? (Um, I don’t really care if it looks familiar,
just keep reading. You’ve come this far.)

//set cust first name
if(cust.FirstName != null)
  txtFirstName.Text = cust.Firstname;
  txtFirstName.Text = "";

Well, with the ?? (a.k.a. coalesce operator) you can trim this down to

txtFirstName.Text = cust.FirstName ?? "";

In T-SQL you can put an unlimited number of commas in the function to
come up with a bunch of values to check. With the ?? operator you can
just string them along, i.e.:

txtFirstName.Text = cust.FirstName ?? cust.LastName ?? cust.Nickname ?? "Name not found";

This can be taken a step further since ?? can be used with primitives.
This makes it very nice when dealing with nullable primitives.
Assuming MetaData has an Occurrence that is a int? you can get the
occurrence like: int occurrence = MetaData.Occurrence ?? 0;

No casting just nice code.
Well, later ‘yall!


Leave a Reply

Your email address will not be published. Required fields are marked *


928 East Plymouth Drive Asbury Park, NJ 07712