Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit all functions from code in inner function

Tags:

c#

If I have nested functions in C#, how to exit from both function at once when executing inner function code. (Return; only exits from executing function.)

public void Function1()
{
    Function2();
}

public void Function2()
{
    if (1 == 1)
    {       
        //Exit from both functions
    }
}
like image 201
Nalaka526 Avatar asked Dec 27 '22 09:12

Nalaka526


2 Answers

Use return codes instead of void functions. Function1 can return if Function2 fails like so:

public void Function1()
{
    if (Function2() == false)
        return;

    // do other code if Function2 succeeded
}

public bool Function2()
{
    if (1 == 1)
    {
        return false;
    }
    else
    {
        return true;
    }
}
like image 87
Trevor Elliott Avatar answered Jan 09 '23 02:01

Trevor Elliott


The only way to return from a stack of functions simultaneously is to throw an exception. An exception will work it's way down the call stack until it finds an appropriate handler.

public class MyException : Exception
{
}

public void FunctionZero()
{
   try
   {
      Trace.WriteLine("Function0 - Calling Function 1");
      Function1();
      Trace.WriteLine("Function0 - Function1 has returned");
   }
   catch(MyExceptionType ex)
   {
      Trace.WriteLine("Function0 - in the exception handler");
   }
}

public void Function1()
{
    Trace.WriteLine("Function1 - Calling Function 2");
    Function2();
    Trace.WriteLine("Function1 - Function2 has returned");
}

public void Function2()
{
    if (1==1)
    {
       // This will jump to the exception handler in function zero
       Trace.WriteLine("Function2 - throwing an exception");
       throw new MyException();
    }
}

Thiw will create the following trace output

Function0 - Calling Function 1

Function1 - Calling Function 2

Function2 - Throwing an exception

Function0 - In the exception handler

While you CAN do this, it's not necessarily a good idea. Standard coding practice is for Exceptions only to be used in exceptional circumstances, and not for normal flow control.

like image 21
Andrew Shepherd Avatar answered Jan 09 '23 03:01

Andrew Shepherd