How to indicate that a method was unsuccessful

c#, methods, return-value

Solution

Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not

`public bool CalculatePoint(... out Point result);`

I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries).

Problem

I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there. Ideally I would like the methods to 'look' similar; one solution could be to define them as ``` public Point CalculatePoint(... out Boolean boSuccess); public List<Point> CalculateListOfPoints(... out Boolean boSuccess); ``` or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive. Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something... What is best practice? Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.

Original source

Related problems