I can think of the following ways to return multiple values from a method (and one which splits into two methods)
private bool IsCarFaulty(Car car, out string fault)
{
fault = string.Empty;
return false;
}
private Tuple<bool, string> IsCarFaulty(Car car)
{
return Tuple.Create(false, string.Empty);
}
private ResultAndMessage IsCarFaulty(Car car)
{
return new ResultAndMessage(false, string.Empty);
}
private bool IsCarFaulty(Car car)
{
return false;
}
private string GetCarFault(Car car)
{
return string.Empty;
}
Basically my question is, are there situations where one is preferable over the other? If I take int.TryParse for an example. It uses an out parameter, but couldn't splitting it into two methods CanParse and Parse work just as well, if not better.
The problem with separate CanParse
and Parse
methods is that you have to pay the cost of parsing twice - once in CanParse
and then again in Parse
. This can be especially problematic when the parsing is quite complex and time-consuming (for example for types like DateTime
).
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