15

Consider i execute a method 'Method1' in C#. Once the execution goes into the method i check few condition and if any of them is false, then the execution of Method1 should be stopped. how can i do this, i.e can the execution of a method when certain conditions are met.?

but my code is something like this,

int Method1() { switch(exp) { case 1: if(condition) //do the following. ** else //Stop executing the method.** break; case2: ... } } 
1
  • Do you want to exit the program after you stop executing? or do you want to return to the calling method? Commented Apr 13, 2009 at 15:02

5 Answers 5

38

Use the return statement.

if(!condition1) return; if(!condition2) return; // body... 
Sign up to request clarification or add additional context in comments.

1 Comment

Or you can say if(!condition1 || !condition2) return;
15

I think this is what you are looking for.

if( myCondition || !myOtherCondition ) return; 

Hope it answered your question.

Edit:

If you want to exit the method due to an error you can throw an exception like this:

throw new Exception( "My error message" ); 

If you want to return with a value, you should return like before with the value you want:

return 0; 

If it is the Exception you need you can catch it with a try catch in the method calling your method, for instance:

void method1() { try { method2( 1 ); } catch( MyCustomException e ) { // put error handling here } } int method2( int val ) { if( val == 1 ) throw new MyCustomException( "my exception" ); return val; } 

MyCustomException inherits from the Exception class.

1 Comment

"== true"? how about ( (myCondition == true) == true )?
3

Are you talking about multi threading?

or something like

int method1(int inputvalue) { /* checking conditions */ if(inputvalue < 20) { //This moves the execution back to the calling function return 0; } if(inputvalue > 100) { //This 'throws' an error, which could stop execution in the calling function. throw new ArgumentOutOfRangeException(); } //otherwise, continue executing in method1 /* ... do stuff ... */ return returnValue; } 

Comments

2

There are a few ways to do that. You can use return or throw depending if you consider it an error or not.

Comments

1

You could setup a guard clause with a return statement:

public void Method1(){ bool isOK = false; if(!isOK) return; // <- guard clause // code here will not execute... } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.