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.

Recommended Answers

All 2 Replies

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 . . .

That's what I figured, but just wanted someone's opinion :)

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.