I'm using a factory to create IComparer<User> objects to sort a list of users.
I have 2 classes : Ascending and Descending, both implement IComparer<User>. Here's the code :
namespace Test { public class Program { public static void Main(string[] args) { List<User> users = new List<User>(); users.Add(new User("foo", "bar")); // ... IComparer<User> cmp = ComparerFactory.GetComparer("FirstName", true); if (cmp != null) { users.Sort(cmp); } } } public class User { public string FirstName { get; set; } public string LastName { get; set; } public User(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } public class UserFirstNameComparer { public class Ascending : IComparer<User> { public int Compare(User u1, User u2) { return String.Compare(u1.FirstName, u2.FirstName, true); } } public class Descending : IComparer<User> { public int Compare(User u1, User u2) { return new UserFirstNameComparer.Ascending().Compare(u1, u2) * -1; } } } public static class ComparerFactory { public static IComparer<User> GetComparer(string fieldName, bool ascending) { switch (fieldName) { case "FirstName": return ascending ? new UserFirstNameComparer.Ascending() : // ERROR IS HERE new UserFirstNameComparer.Descending(); //... } return null; } } But I get an error (line : new UserFirstNameComparer.Ascending() :) :
Type of conditional expression cannot be determined because there is no implicit conversion between 'Test.UserFirstNameComparer.Ascending' and 'Test.UserFirstNameComparer.Descending'
I dont understand what it means, both are IComparer objects, so what's the problem ? The weird thing is that I can fix the error with a (unnecessary ?) cast :
// This works return ascending ? (IComparer<User>) new UserFirstNameComparer.Ascending() : new UserFirstNameComparer.Descending(); // This works too return ascending ? new UserFirstNameComparer.Ascending() : (IComparer<User>) new UserFirstNameComparer.Descending(); Of course it works when I cast in both cases. But I do not understand why it works with only one cast, and why it does not when there is no cast. Any ideas ?
(I'm using VS 2012, .NET v4.0.30319)
Comparers(which is very silly), why don't you just create one regularComparer(ascending) and do list.Sort(cmp).Reverse() or list.OrderBy(cmp) / list.OrderByDescending(cmp)?-1as you do above, will not work as desired if the return value of theComparecall is-2147483648. SomeCompareimplementations do return other values than just-1,0and+1, and are allowed to do so.