Returning multiple values from a method

c#

Solution

Basically my question is, are there situations where one is preferable over the other?

Sure, but I don't think there is a general rule that applies to all cases. Just pick the one you feel more comfortable with on a case by case basis.

I usually avoid using `out` parameters, because they don't play well with Linq.

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.

Sure, it could work, but that means the string would be parsed twice, which is suboptimal.

When int.TryParse was introduced, C# didn't have nullable types (EDIT: actually it did); now you could write a method like that:

public static int? TryParseInt32(string s)
{
    int i;
    if (int.TryParse(s, out i))
        return i;
    return null;
}

Problem

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.

Original source