Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant check for null and exit in C#

What is an elegant way of writing this?

if (lastSelection != null)
{
    lastSelection.changeColor();
}
else
{
    MessageBox.Show("No Selection Made");
    return;
}

changeColor() is a void function and the function that is running the above code is a void function as well.

like image 371
Aishwar Avatar asked Mar 14 '10 03:03

Aishwar


1 Answers

You can reduce clutter by reversing the condition:

if (lastSelection == null)
{
    MessageBox.Show("No Selection Made");
    return;
}

lastSelection.changeColor();
like image 120
Bevan Avatar answered Sep 23 '22 15:09

Bevan