Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

coalesce

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

like image 687
Matt Chambers Avatar asked Oct 24 '11 20:10

Matt Chambers


2 Answers

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);
}
like image 97
driis Avatar answered Oct 10 '22 11:10

driis


No basically, but it would be nice if it did (IIRC, Jon mentioned a similar idea in C# in Depth). You could probably chain conditionals, but I tend to just use:

int delta = Bar.CompareTo(rhs.Bar);
if(delta == 0) delta = Baz.CompareTo(rhs.Baz);
if(delta == 0) delta = Fuz.CompareTo(rhs.Fuz);
return delta;
like image 32
Marc Gravell Avatar answered Oct 10 '22 10:10

Marc Gravell