Can I use the coalesce operator on integers to chain CompareTo?
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;
Not really, ??
only works for null values (reference types or nullable structs)
int i;
i = Bar.CompareTo(rhs.Bar);
if (i != 0) return i;
i = Baz.CompareTo(rhs.Baz);
if (i != 0) return i;
i = Fuz.CompareTo(rhs.Fuz);
if (i != 0) return i;
return 0;
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);
}