In the .NET Framework (around the advent of generics), the Try[method] pattern emerged to help deal with the situation where an operation needed to indicate it failed to complete successfully without throwing an exception.
In situations where failure is considered normal (such as parsing) and not exceptional, this is obviously a desirable pattern to follow.
However, if a method can return null to indicate it failed to get a value successfully (such as in the case of a Find method), is this considered more correct than a TryFind method which clearly indicates success or failure with a return value? Is there any precedent set by the .NET Framework to this pattern?
I believe the TryX pattern pre-dates Nullable<T> types, which were added in .NET 2.0. Nullable<T> solved the problem of value types and the potential discrepancies between whether the default type value was valid/invalid. However, even with these additions, I do believe the TryX pattern still holds value.
The two major benefits of the TryX pattern are:
Nullable<T> types remove ambiguity but do not provide exception safety.
I don't believe there is a concrete precedence set, but if your method needs to guarantee these, then I would use the TryX pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With