Gabriel Weidmann
Gabriel Weidmann

Reputation: 887

C# - Can/Should I simplify/alter this code snippet?

I got the following code in my program:

#region Handle

    if(HandleLink(input))
        goto Handled;
    else if(HandlePath(input))
        goto Handled;
    else if(HandleGeneratedLink(input))
        goto Handled;
    else ...
    else
        return; // Break if not handled

#endregion

Handled:

Im not very happy with this, because to me it seems like a cheat to use a goto in every second line. Is there a common way to write such a thing or is this a valid solution?

Upvotes: 0

Views: 47

Answers (3)

Jek
Jek

Reputation: 461

You can also do something like this:

if (!HandleLink(input) && !HandlePath(input) && !HandleGeneratedLink(input)) {
    return;
}
// put the code related to "Handled" here

Upvotes: 2

Sweeper
Sweeper

Reputation: 271820

You can do something like this:

if (HandleLink(input) || HandlePath(input) || HandleGeneratedLink(input)) {
    // put the code below the "Handled" label here
} else {
    return;
}

Since the || evaluates the right operand only if the left operand is false, HandlePath() will not be called when HandleLink() returns true. It works just like your if...else if statement!

Alternatively, you can make a variable called handled:

var handled = false;
if (HandleLink(input) || HandlePath(input) || HandleGeneratedLink(input)) {
    handled = true;
} else {
    return;
}

if (handled) {
    // move the code below the "Handled" label here.
}

Upvotes: 1

Ritwik Sen
Ritwik Sen

Reputation: 296

Try this

if(HandleLink(input) || HandlePath(input) || HandleGeneratedLink(input))
 goto Handled;
else
 return;

Upvotes: 0

Related Questions