Implement an interface in C#

An interface defines features of a class without providing any implementation. Sometimes if you implement an interface, you can take advantage of features that know how to use the interface.

For example, the IComparable interface requires that a class provide a CompareTo method that compares the object to another object. If you implement the IComparable interface in a class, then the Array.Sort method can sort an array of those objects.

To indicate that a class implements an interface in the class's declaration, follow the class name by a colon and the interface's name as in:

class SortablePerson : IComparable
{
...
}

Now you need to provide the methods that the interface requires. You can type those in from memory but there's a much easier way. Click on the interface's name and look for a little auto-correct bar (see the arrow in Figure 1). Hover over that bar to display a dropdown arrow. Click the arrow and select the first command as shown in Figure 2.

At that point, Visual Studio fills in empty methods required by the interface. For the IComparable interface, Visual Studio adds the following code to the class:

#region IComparable Members

public int CompareTo(object obj)
{
throw new NotImplementedException();
}

#endregion

This entry's example uses the following SortablePerson class.

class SortablePerson : IComparable
{
public string FirstName, LastName;

public override string ToString()
{
return LastName + ", " + FirstName;
}

public int CompareTo(object obj)
{
SortablePerson other = obj as SortablePerson;
return this.ToString().CompareTo(other.ToString());
}
}

This class has simple FirstName and LastName fields. It overrides its ToString method to return the person's name as in "Stephens, Rod."

The implementation of the CompareTo method compares the ToString values of one SortablePerson and another.

The following code shows how the example makes an array of SortablePersons, sorts it, and displays the result in a ListBox.

SortablePerson[] sorted = 
{
new SortablePerson() { FirstName = "Sally", LastName = "Cherry" },
new SortablePerson() { FirstName = "Alice", LastName = "Beech" },
new SortablePerson() { FirstName = "Mark", LastName = "Ash" },
new SortablePerson() { FirstName = "Christine", LastName = "Beech" },
new SortablePerson() { FirstName = "Phred", LastName = "Cherry" },
};

Array.Sort(sorted);

lstSorted.DataSource = sorted;

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.