How to terminate a method execution Midway in C#?
Olivia Zamora
I need to exit from a method when a certain condition is reached. The other lines of code should not be executes after exit Condition is reached. what is the best way for this I have tried to use Environment.Exit(0), but it causes problem in my logic.
Exit(0) does not seem to work unless in a loop
3 Answers
We have two possibilities: normal (return) and abnormal (throw) termination:
public static int Factorial(int value) { // We can't compute factorial for negative and too large values if (value < 0 || value > 12) throw new ArgumentOutOfRangeException(nameof(value)); // Abnormal termination if (value == 0) return 1; // Normal termination: special case in which we know the answer ... } 1 The "return" statement exits condition-blocks aswell as loops and methods.
public void myMethod(int a){ if( 1 == a) { return; } // do something with a
} 3 As some people have already said before me, return is the way to go. Here is an example where an if statement compares two integers and returns if they are equal:
public void isEqual(int a, int b) { if (a == b) { Console.WriteLine("Integers are equal"); return; //Return to executing the rest of the program. } else { Console.WriteLine("Integers are not equal"); }
} 5