Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning multiple values from a method

Tags:

c#

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.

like image 598
JKF Avatar asked Aug 17 '12 23:08

JKF


1 Answers

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).

like image 134
Mark Byers Avatar answered Sep 23 '22 02:09

Mark Byers