Geeks With Blogs
Create Fun Things - Samer's Developer Blog Development Blog for C#, .NET and Obj-C

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

Posted on Thursday, September 24, 2009 9:50 AM | Back to top


Comments on this post: Quick Tip: If/else shortcut

# re: Quick Tip: If/else shortcut
Requesting Gravatar...
Prefer the first version - much more readable even if it does take more lines of code.
Left by Greg Suttie on Sep 25, 2009 1:43 AM

# re: Quick Tip: If/else shortcut
Requesting Gravatar...
Cool. Can you do this with an if/else if/else statement?

Thanks!

Noah
Left by Noah on Sep 04, 2011 1:12 PM

Your comment:
 (will show your gravatar)


Copyright © samerpaul | Powered by: GeeksWithBlogs.net