Tips and tricks (2)

The ?? operator is called the null-coalescing operator and is not very well-known, but can be very useful sometimes to define default values for types as in the following example:

int? number1 = null;
// number2 = number1, unless number1 is null, in which case number2 = -1
int number2 = number1 ?? -1;

If number1 is null then number2 will be set to -1, if number1 is not null, number2 will get the value of number1. A useful case where this can be applied is in properties, to guarantee that a collection is initialized:

private List<int> numbers = null;
public List<int> Numbers
{
get { return numbers ?? new List<int>(); }
}

You can even do a number of comparisons in one line of code:

DateTime? dateTime1 = null;
DateTime? dateTime2 = null;
DateTime? dateTime3 = DateTime.Now;
DateTime dateTime = dateTime1 ?? dateTime2
?? dateTime3 ?? DateTime.MinValue;

This obviously avoids a large block of if-then-else statements.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s