Information Technology Reference
In-Depth Information
So how can you make the
Sort
method work with objects of type
MyClass
? To implement
an interface, a class or struct must do two things:
It must list the interface name in its base class list.
It must provide an implementation for each of the interface's members.
For example, the following code updates
MyClass
to implement interface
IComparable
.
Notice the following about the code:
The name of the interface is listed in the base class list of the class declaration.
The class implements a method called
CompareTo
, whose parameter type and return type
match those of the interface member.
Method
CompareTo
is implemented following the definition given in the interface's doc-
umentation. That is, it returns a negative 1, positive 1, or 0, depending on its value
compared to the object passed into the method.
Interface name in base class list
↓
class MyClass : IComparable
{
public int TheValue;
public int CompareTo(object obj) // Implementation of interface method
{
MyClass mc = (MyClass)obj;
if (this.TheValue < mc.TheValue) return -1;
if (this.TheValue > mc.TheValue) return 1;
return 0;
}
}
Figure 17-2 illustrates the updated class. The arrow from the grayed interface method
to the class method indicates that the interface method does not contain code, but is imple-
mented by the class-level method.
Figure 17-2.
Implementing IComparable in MyClass