- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 292字
- 2025-04-04 18:04:55
Implementing the interface
Next, because IComparable has a function, right-click on it, select Quick Actions, and choose Implement interface from the popup. Now, we have to write code.
First, delete throw new NotImplementedException(). Now, we will implement the interface in a way that's sufficient to illustrate the point. For this, enter the following beneath the open curly brace under the public int CompareTo(Quad other) line:
if(this.name.CompareTo(other.name) <0)
Here, this means the current object, and the name of this object is compared to other.name, meaning the other object. Look at where it says (Quad other) in the line above this one; in other words, we're comparing two Quads. So, in the one on the left, this is the one on which the function is being invoked and the other Quad class is the one against which it's being compared. So, if this is less than 0, we will return a number such as -1, else it can return some other value, such as 1. Enter the following between a set of curly braces below this line:
{
return -1;
}
else
{
return 1;
}
We have just implemented CompareTo. Now, notice that the this is not necessary. You can remove it and it will still work. Remember, however, that name essentially means the current object under which CompareTo will be invoked. This is why I like to have the this keyword present, because it is more suggestive of what I want to know.
Basically, what this line is saying is that if the current object when compared to the other name is less than 0, then we return -1, which means that the current object will come before the next object in the list when you sort it. That's a simple interpretation.