+ 3

How do I return nothing in function with return type double.

I use a function with return type double and i want to return nothing (not zero). EDIT:My code looks like this and in case of error i want the console to output the error message only(but it wont allow me as it requires value to return) public double pop() { if (--position<0) { Console.WriteLine("There are no elements in Stack"); //here I should insert sth } else return Sztos[position]; }

28th Feb 2018, 10:15 PM
ThePigeon109
9 Answers
+ 14
make that return type of that function be void then...
28th Feb 2018, 9:45 PM
Vukan
Vukan - avatar
+ 7
If c# supports exceptions, generate one and correctly handle it at a point it makes the most sense in the call chain.
28th Feb 2018, 10:09 PM
John Wells
John Wells - avatar
+ 7
What we did before exceptions existed, was return a boolean plus double in a structure. If the boolean was true, the double was valid. Otherwise, the caller did it's error handling. If it couldn't finish it's processing correctly, it passed it to it's caller. This got very complex, which is one reasons exceptions were invented.
28th Feb 2018, 11:16 PM
John Wells
John Wells - avatar
+ 5
Could you post the full code? one option is that you could have a default value, like -1.0 that, in the main function, would have an if statement to test the return for that value. not the best solution, and it may not work depending on what your code does with the value, but if you don't want to change the return type or catch exceptions (which is the best option), then you could do it
28th Feb 2018, 10:55 PM
J.G.
J.G. - avatar
+ 3
You can't. You have to change the return type. That's what type systems are for.
28th Feb 2018, 9:42 PM
1of3
1of3 - avatar
+ 3
Since the NaN constant exists, it could be returned when your error occurs and you don't have a valid double. The caller, of course, should test for it.
2nd Mar 2018, 4:32 AM
John Wells
John Wells - avatar
+ 1
If you don't want to return a double then don't use the return type double. Use the void return type and you don't even have to specify a return statement.
2nd Mar 2018, 4:16 AM
Ben Allen (Njinx)
Ben Allen (Njinx) - avatar
0
And nowadays the cool kids do the monads. Which is safe in such a, way that you cannot ignore it, and simple as long as you chain but not stack them.
1st Mar 2018, 5:30 AM
1of3
1of3 - avatar
0
an double type function can't return null. only numbers type double or zero
1st Mar 2018, 6:42 PM
Catalin Popinciuc
Catalin Popinciuc - avatar