0

Simple question: is it a performance issue or bad form to have if statements without a else following?

As an example, an event that is triggered when a listbox selected index changes depends on the selected index value to run, and during the change, the value switches from some integer to a null value then back to an integer. To prevent an exception in the event method because of a null value, is it bad to have the following at the start of the event:

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (someString == null)
            {
                return;
            }
        // Do stuff...
    }

or is it better to do:

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (someString == null)
            {
                return;
            }
        else
            {
                // Do stuff...
            }
    }

Or does it even make a difference?

Personally it's just a formatting issue for me, the else block pushes all of the other code over two indentations causing some of the code that would be in the else block wrap around the screen and I cant stand that the wrapped code doesn't line up with the rest of it.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by zachattack05
1

The example you've given is fine and won't cause any problems because you've used return which will jump out of the method from that return keyword.

If you didn't have the return or break key word and just had some code like set a bool variable to true then it would continue executing the code after the if statement once the if statement is complete.

hope this helps . . .

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.