Priyanka
Priyanka

Reputation: 617

Exit from a function in C#

A basic question. I need to exit a function without throwing any exceptions. How do I do that in C#?

Upvotes: 17

Views: 45506

Answers (6)

Florian Greinacher
Florian Greinacher

Reputation: 14786

It's as simple as:

void Function()
{
    ...

    if(needToLeave)
        return;

    ...
}

Upvotes: 33

Nwaoga
Nwaoga

Reputation: 51

Use the return or break keywords ...... But make sure nothing is after these statements as you may have unreachable code. Also having multiple exits in your code can make it difficult to maintain in the future

Upvotes: 0

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

Instead of using "return;" I've always suggested a right logic.

In other words, you don't need to leave execution from some method: just use a conditional statement so if some boolean isn't true, that would mean some code mustn't be executed.

But I assume this is my opinion, and others prefer returning the control to the caller.

Additionally, you'd like to know exception-based flow control is an anti-pattern.

Upvotes: 2

Kishore Borra
Kishore Borra

Reputation: 269

you can put you code in a try catch block and do whatever you want to do in the finally block without worrying about the exception.

 try
        {
         //try something   
        }
        catch(Exception ex)
        {
            //catch all exceptions and log on need basis
            //but do not throw the exception from here
        }
        finally
        {
            return "Test";
            //do what ever you want to do 
        }

Upvotes: -1

Pankaj
Pankaj

Reputation: 10095

May be to Keep the catch block empty. Please explain your question

Upvotes: -3

Kamyar
Kamyar

Reputation: 18797

I'm not sure I understand you correctly. Maybe using return;?

Upvotes: 10

Related Questions