tim
tim

Reputation: 197

how to break out of "if" block in VB.NET

How can I break out of an if statement?

Exit only works for "for", "sub", etc.

Upvotes: 8

Views: 43243

Answers (6)

David M.
David M.

Reputation: 1

I have to admit, that in some cases you really wanna have something like an exit sub or a break. On a rare occasion is I use "Goto End" and jump over the "End If" with the def. End:

Upvotes: 0

user1218427
user1218427

Reputation: 17

You can use

bool result = false;
if (i < 10)
{
    if (i == 7)
    {
        result = true;
        break;
    }
}

return result;

Upvotes: 0

Ashar
Ashar

Reputation: 11

I know this is an old post but I have been looking for the same answer then eventually I figured it out

        try{

            if (i > 0) // the outer if condition
            {
                Console.WriteLine("Will work everytime");
                if (i == 10)//inner if condition.when its true it will break out of the outer if condition
                {
                    throw new Exception();
                }
                Console.WriteLine("Will only work when the inner if is not true");
            }
        }
        catch (Exception ex)
        {
            // you can add something if you want
        }

`

Upvotes: -3

thelost
thelost

Reputation: 6694

In C# .NET:

if (x > y) 
{
    if (x > z) 
    {
        return;
    }

    Console.Writeline("cool");
}

Or you could use the goto statement.

Upvotes: 2

Tom Gullen
Tom Gullen

Reputation: 61773

In VB.net:

if i > 0 then
   do stuff here!
end if

In C#:

if (i > 0)
{
  do stuff here!
}

You can't 'break out' of an if statement. If you are attempting this, your logic is wrong and you are approaching it from the wrong angle.

An example of what you are trying to achieve would help clarify, but I suspect you are structuring it incorrectly.

Upvotes: 8

Radu
Radu

Reputation: 8699

There isn't such an equivalent but you should't really need to with an If statement. You might want to look into using Select Case (VB) or Switch (C#) statements.

Upvotes: 2

Related Questions