c# return that also returns the calling function similar to PHP's die() early out

Note: This is a question from the PHP perspective for C#. Maybe it isn't the right way to do it, but here is what I'm trying to do.

Suppose you have defined:

void Die(string error){
 print(error);
 return; 
}

And you call it from another method:

void CallingFunction(){
  if(SomethingDoesNotCheckOut())
   Die("bla");

  // do stuff
}

is it possible to have Die() also trigger an early out in the "parent" method that calls it?


One example:

void CallingFunction(){
  if(index>arrayLength)
   Die("that's too big!");

  // do stuff
}

It seems try-catch is overkill for this, but I'd rather be able to just call a function that will just stop the current "parent" function. Maybe I'm thinking too much like PHP's die()

Jon Skeet
people
quotationmark

Not without throwing an exception, no. Bear in mind that in many cases the calling method will be non-void - in that case, what value would you expect it to return?

The use case you're describing does sound like it would be better handled with an exception anyway, to be honest. That's the C# idiomatic error handling mechanism.

If you want to collect errors without using exceptions, you'll have to return explicitly.

people

See more on this question at Stackoverflow