In C++ if I want to exit a method without returning anything I can do;
// A completely useless method static public double function(int a){ if(a==1){ cout << "Error !"; exit(1); } else return (double)a; } How can I do the equivalent in C# ?
In C++ if I want to exit a method without returning anything I can do;
// A completely useless method static public double function(int a){ if(a==1){ cout << "Error !"; exit(1); } else return (double)a; } How can I do the equivalent in C# ?
The usual way of handling an error condition in .NET is to throw an exception:
public static double function(int a) { if (a == 1) { throw new ArgumentException("The value 1 is not accepted."); } return (double)a; } The exception would be caught by the code calling the method, or somewhere down the line. It's up to the calling code to handle it at an appropriate level.
It's quite usual for methods to sanitise the input in this manner, so that any faulty values are caught early instead of causing an error later in the code where it is much harder to track down.
The "exit" function doesn't just exit the method - it terminates the program.
http://msdn.microsoft.com/en-us/library/k9dcesdd.aspx
In C# Console Applications, you could call System.Environment.Exit().
But I would suggest that any code doing this could be written with much better structure. For example, your method could throw an exception, and let the caller decide how to handle it.
That would certainly be an odd thing to do, but yeah - you could call Environment.Exit. I'd strongly suggest throwing an Exception instead though. That gets you a chance to cleanup, and your caller can decide how to handle the error. If nobody does, you'll still bring down the process - but somewhat more gracefully.
Considering the context of what you want to do, this should be the equivalent:
public static double SomeFunction(int a) { if(a==1) { throw new Exception("Error!"); } else { return (double)a; } } try return to exit out of the method without exiting the whole program.
You don't. By following your method, you'd have to do a test after every call to your function, to check if a double was in fact returned.
In your example, you'd do something like...
public static double myFunc( int a ) { if( a==1 ){ throw new InvalidArgumentException( "a must be greater than one." ); } return (double)a; }