Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a "Try" method preferred over a "null" result?

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?

like image 317
Paul Turner Avatar asked Mar 21 '26 23:03

Paul Turner


1 Answers

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:

  • No ambiguity of return value.
  • Safety from exceptions.

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.

like image 141
ahawker Avatar answered Mar 25 '26 02:03

ahawker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!