September 13, 2007

C# 2.0: ? Operator and Anonymous Methods

Nothing too big with this one. If you are using the ? operator, the return types can't be anonymous methods.

This code will fail to compile with the message "Type of conditional expression cannot be determined because there is no implicit conversion between 'anonymous method' and 'anonymous method'":
results.Sort(GridViewSortDirection == "ASC" ?
delegate(MyClass p1, MyClass p2) { return p1.CompareMe.CompareTo(p2.CompareMe); } :
delegate(MyClass p1, MyClass p2) { return p2.CompareMe.CompareTo(p1.CompareMe); });

To get around it, break it out into a standard "if":
if (GridViewSortDirection == "ASC")
results.Sort(delegate(MyClass p1, MyClass p2) { return p1.CompareMe.CompareTo(p2.CompareMe); });
else
results.Sort(delegate(MyClass p1, MyClass p2) { return p2.CompareMe.CompareTo(p1.CompareMe); });

No comments: