Lucina
Lucina

Reputation: 490

Specifying that a function does not return in C#

Is there any way to tell the C# compiler that a function never returns? I'm running into the following problem. This is a boiled down version for simplicity.

public int myMethod()
{
    try
    {
        return anythingHere();
    }
    catch
    {
        Environment.Exit(1); //or a function which always either calls Environment.Exit or throws an exception
    }
}

'package.class.myMethod()' not all code paths return a value.

If not, is there a general way to frame this sort of thing other than inserting unreachable code? Having a 'return 0' or somesuch after the Exit just seems ridiculous to me. As far as I know there is no way that a function can return from an Environment.Exit call, so no return value is needed if that branch is taken (if it threw an exception the function still wouldn't need to have returned a value).

EDIT:

Maybe something like this?

public T MyExit<T>()
{
    Environment.Exit(1);
    return default(T);
}

Still not entirely satisfactory though.

Upvotes: 0

Views: 2726

Answers (5)

James
James

Reputation: 7543

I'm not sure if it's what you're looking for, but this would avoid unreachable code:

public int myMethod()
{
  int retVal = 0;
  try {
    retVal = anythingHere();
  } catch {
    Environment.Exit(1);
  }
  return retVal;
}

Upvotes: 2

Paul Stovell
Paul Stovell

Reputation: 32745

It might be better to throw an exception than to call Environment.Exit. If someone else used your class, and their process suddenly shut down, they'd be pretty surprised. By throwing an exception you can at least explain why the problem happened.

At the top level entry point of your app (i.e., Main) you could then set up a global exception handler (AppDomain.UnhandledException) that handles all exceptions and calls Environment.Exit.

Upvotes: 1

Ralph Lavelle
Ralph Lavelle

Reputation: 5769

Make the method void, and pass in an object that contains the 'anythingHere' type of information you need as an out type, so that it can be set, but the method itself won't actually return anything.

public void myMethod(out anythingObject)
{
    try
    {
        anything = new anythingObject(stuff goes here); 
    }
    catch
    {
        Environment.Exit(1); //or a function which always either calls Environment.Exit or throws an exception
    }
}

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

Make it a void, instead of an int.

public void myMethod(out int i)
{
    try
    {
       i = anythingHere();
    }
    catch
    {
        Environment.Exit(1);
    }
}

Upvotes: 0

Related Questions