Quick Tip: If/else shortcut

Today is just another quick tip of something that took me a while to embrace, but once I did, I can’t live without it.

Here’s an example. I have a try/catch block in my code for a button that runs a database process. I want it to catch any exceptions that come back and handle them by printing the message to the user. (Just a real rudimentary example to show how to use this shortcut:)

catch(Exception ex)
        {
            if (ex.InnerException != null)
            {
                StatusLabel.Text = ex.InnerException.Message;
            }
            else
            {
                StatusLabel.Text = ex.Message;
            }

 

That’s pretty verbose, especially if you find you write this a lot…so why not instead do:

StatusLabel.Text = ex.InnerException != null
                ? ex.InnerException.Message
                : ex.Message;

So that looks pretty crazy. What all is going on in there? Well, it really helped me to start reading those statements like:

 

Status Label Text = If Inner Exception is not Null
THEN Make the text the InnerException Message,


OTHERWISE make it the base exception’s message.

 

In even shorter terms, it reads basically like this:

output = Condition ? If True : If False

I really like this, because it means you can do in-line if/else statements, which is a huge help for keeping your code small and tidy. Here’s an example:

StatusLabel.Text = string.Format("an error has occurred!: {0}",
                ex.InnerException != null ? ex.InnerException.Message : ex.Message);

I have the status label’s text property output the inner exception message if it’s not null, or the base exception’s message if it is null. And I can do it inside a string.Format() method call, which is even cooler.

Cheers!

samer paul

Print | posted on Thursday, September 24, 2009 9:50 AM

Feedback

# re: Quick Tip: If/else shortcut

left by Greg Suttie at 9/25/2009 1:43 AM Gravatar
Prefer the first version - much more readable even if it does take more lines of code.

# re: Quick Tip: If/else shortcut

left by Noah at 9/4/2011 1:12 PM Gravatar
Cool. Can you do this with an if/else if/else statement?

Thanks!

Noah
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: