I understand how to use the IComparer interface with helper classes that provide custom sorting methods. For example, here is a typical example that is very similar to all the examples I've seen on the Internet, including the Microsoft help page:
// This helper class is used to sort an array of people by name, // where 'Person' is a class type. public class PeopleNameComparer : IComparer { // Test the name of each object. int IComparer.Compare(object o1, object o2) { Person p1 = o1 as Person; Person p2 = o2 as Person; if (p1 != null && p2 != null) return string.Compare(p1.Name, p2.Name); else throw new ArgumentException("Parameter is not a Person!"); } }
I also understand that if we have an array of type Person (myPeople), we can sort this array with:
Array.Sort(myPeople, new PeopleNameComparer());
In this case, we create a new PeopleNameComparer object that is of type IComparer and passes it to the Array.Sort () method as the second parameter.
Now, to make things tidy, we can implement a property to provide the user of the object with a more convenient way to invoke custom sorting:
public static IComparer SortByName { get { return (IComparer)new PeopleNameComparer(); } }
What I donโt understand with this property is why all the examples use (IComparer) cast to include the newly created helper class (PeopleNameComparer in this example) in the IComparer object when this object already has an IComparer type? I tried without casting and the code works fine:
// This property seems to work fine without the cast? public static IComparer SortByName { get { return new PeopleNameComparer(); } }
I could understand this if the 'new' keyword returned the normal System.Object vanilla type, which then had to be sent to the appropriate IComparer, but just can't see the need for a cast here. But I followed the example of Microsoft, and my example is similar to the example in my Pro C # book.
Is there any reason why a shot is needed here?