Search code examples
c#.netperformanceclarity

Is it better to use out for multiple output values or return a combined value type?


For instance, along the lines of:

public bool Intersect (Ray ray, out float distance, out Vector3 normal)
{

}

vs

public IntersectResult Intersect (Ray ray)
{

}

public class IntersectResult
{
    public bool Intersects {get;set;}
    public float Distance {get;set;}
    public Vector3 Normal {get;set;}
}

Which is better both for clarity, ease of use, and most importantly performance.


Solution

  • I would use a combined type.

    With an object you can attach behaviour, and return an arbitrarily complex object. You may wish to refactor your method in the future, and change the return values. By wrapping them in a return object and adding behaviour to that object, this refactoring can become largely transparent.

    It's tempting to use tuples and the like. However the refactoring effort becomes a headache after a while (I'm speaking from experience here, having just made this mistake again)