Information Technology Reference
In-Depth Information
.NET 2.0. That means supporting the pregeneric interface. Second, even
more modern code will avoid generics when it's based on reflection.
Reflection using generics is possible, but it's much more difficult than
reflection using nongeneric type definitions. Supporting the nongeneric
version of the IComparable interface makes your type easier to use for
algorithms making use of reflection.
Because the classic IComparable.CompareTo() is now an explicit interface
implementation, it can be called only through an IComparable reference.
Users of your customer struct will get the type-safe comparison, and the
unsafe comparison is inaccessible. The following innocent mistake no
longer compiles:
Customer c1;
Employee e1;
if (c1.CompareTo(e1) > 0 )
Console .WriteLine( "Customer one is greater" );
It does not compile because the arguments are wrong for the public
Customer.CompareTo(Customer right) method. The IComparable
.CompareTo(object right) method is not accessible. You can access the
IComparable method only by explicitly casting the reference:
Customer c1 = new Customer ();
Employee e1 = new Employee ();
if ((c1 as IComparable ).CompareTo(e1) > 0 )
Console .WriteLine( "Customer one is greater" );
When you implement IComparable, use explicit interface implementation
and provide a strongly typed public overload. The strongly typed overload
improves performance and decreases the likelihood that someone will mis-
use the CompareTo method. You won't see all the benefits in the Sort func-
tion that the .NET Framework uses because it will still access CompareTo()
through the interface pointer (see Item 22), but code that knows the type
of both objects being compared will get better performance.
We ' l l m a k e o n e l a s t s m a l l c h a n g e t o t h e Cu s t o m e r struct . The C# lan-
guage lets you overload the standard relational operators. Those should
make use of the type-safe CompareTo() method:
public struct Customer : IComparable < Customer >, IComparable
{
private readonly string name;
 
Search WWH ::




Custom Search