Aidan Quinn
Aidan Quinn

Reputation: 1188

How can I stop executing the rest of a method at some point inside the method?

I was wondering if there is a command which would have the same function as exit.

So, for instance:

if (Average < 35)
{
    MessageBox.Show("you failed");
    **EXIT**
}

if (Average >= 75)
{
    lblOutput.Text += Name +" " + Surname + ", " + "your average was: " + Average + ", you shall recieve a bursary!";
}
else
    lblOutput.Text += Name +" " + Surname + ", " + "your average was: " + Average + ", you shall not revieve a bursary!";

Even if the average is lower than 35, the script will carry on going and the lblOutput will still say You shall not receive a bursary. while it should just show the MessageBox and not do anything with the label.

Could someone explain how to do this?

Upvotes: 0

Views: 787

Answers (4)

James
James

Reputation: 82096

Alternatively to using return to exit early, you could write your if statements in such a way that it naturally follows that code path

if (Average >= 75)
{
    lblOutput.Text += Name +" " + Surname + ", " + "your average was: " + Average + ", you shall recieve a bursary!";
}
else if (Average >= 35)
{
    lblOutput.Text += Name +" " + Surname + ", " + "your average was: " + Average + ", you shall not revieve a bursary!";
}
else
{
    MessageBox.Show("you failed");
}

For me this is better from a readability point of view.

Upvotes: 1

Tsukasa
Tsukasa

Reputation: 6552

Instead or return just do

if()
{
}
else
{
}

Upvotes: 0

Habib
Habib

Reputation: 223207

I suppose that current code reside in a method with return type void, you can simply use return;

if (Average < 35)
{
    MessageBox.Show("you failed");
    return;
}

Upvotes: 1

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

You can use return; to stop the execution path.

Upvotes: 4

Related Questions