8

How can I break out of an if statement?

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

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
tim
  • 197
  • 1
  • 2
  • 10

6 Answers6

8

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.

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
2

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.

Radu
  • 8,561
  • 8
  • 55
  • 91
2

In C# .NET:

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

    Console.Writeline("cool");
}

Or you could use the goto statement.

thelost
  • 6,638
  • 4
  • 28
  • 44
  • 1
    Also you could throw an exception and catch it outside of `if`. Or just terminate the process :) – RocketR Jul 16 '11 at 20:34
  • Regarding the `goto` command, please read this: http://stackoverflow.com/questions/46586/goto-still-considered-harmful – Gertsen Feb 18 '16 at 15:19
0

You can use

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

return result;
Breeze
  • 2,010
  • 2
  • 32
  • 43
0

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:

-3

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
        }

`

Ashar
  • 11
  • 8
    bad idea to use exceptions for flow of control. They're slow. – Kate Gregory Nov 07 '11 at 14:04
  • 3
    Adding to what @KateGregory said, exceptions should only be used when the program enters a rare, error, or unexpected state. Using exceptions for means of flow control is harder to read, confusing, and less understandable for others. – Daryl Apr 26 '12 at 19:47
  • 1
    better use `Exit Try` (VB), may be `break` in C# – Ivan Ferrer Villa Nov 26 '15 at 15:43