Search code examples
c#if-statementreturngoto

In my C# project,I want to exit Method1 on a specific condition, and execute Method2 without coming back to Method1 again. How can I do that?


In my C# project, I want to exit Method1 on a specific condition and execute another method (Method2) without return back to Method1. I want to prevent using jump statements (goto). How can I do that?

My simplified code looks like

 public void Method1 ()
 {
   if (condition==true)
    {
      Method2() // Here at this point I want to exit Method1 and execute Method2. That means after executing Method2 the program shall not return to Method1. How can I do that?
    }
   //some code
 }

Solution

  • As mentioned in the comments you can return after the method call.

    if (condition == true)
    {
        Method2();
        return;
    }
    

    Alternatively, you can put else for this if statement so that it will run only Method2() if it goes inside the if.

    if (condition == true)
    {
        Method2();
    }
    else
    {
        //Do something
    }
    

    Another way is to have to same return type (except void) (if applicable) for both methods and return like below.

    if (condition == true)
    {
        return Method2();
    }