Matt Chambers Matt Chambers - 3 months ago 13
C# Question

Can I use the coalesce operator on integers to chain CompareTo?

I want to do something like this:

public override int CompareTo (Foo rhs)
{
return Bar.CompareTo(rhs.Bar) ??
Baz.CompareTo(rhs.Baz) ??
Fuz.CompareTo(rhs.Fuz) ?? 0;
}


This doesn't work as written; is there some minimal workaround to make it work? Basically I want 0 to chain until non-zero (or end of chain).

Answer

Not supported by the language. But you can write a small helper like this:

public override int CompareTo (Foo rhs)
{
    return FirstNonZeroValue(
        () => Bar.CompareTo(rhs.Bar), 
        () => Baz.CompareTo(rhs.Baz),
        () => Fuz.CompareTo(rhs.Fuz));
}

private int FirstNonZeroValue(params Func<int>[] comparisons)
{
    return comparisons.Select(x => x()).FirstOrDefault(x => x != 0);
}