Interfaces

An interface is a contract. It defines a standard set of properties, methods, and events that are to be found in any class that implements the interface. This insures that if your class for example implements IWidget, any other class that expects to interact with IWidget can interact with your class, regardless of what other functions your class may perform.

Interfaces and their member functions and properties are implemented in Visual Basic using the Implements keyword. In C#, interfaces to be implemented follow a colon (:) in the class declaration and are separated on a single line by commas.

The property and method definitions must take the exact form defined by the interface. For example, say you were implementing the following interface:

 

// C#
public interface IAccount
{
   void DeductFees(IFeeSchedule feeSchedule);
   void PostInterest();
   decimal Balance
   {
      get;
      set;
   }
}

In the code that you would write to implement these properties and methods, you would have to follow the construction of these procedures exactly. For instance, the following line would be illegal:

 

// C#
double IAccount.MyBalance

This line is not a legal implementation of the interface because it declares the property as a double, instead of an integer. Likewise, a method must take the same number and type of arguments as are defined in the interface. It also has to have the same name.

To implement an existing interface

  1. Declare a class using the standard syntax.
  2. Within the class declaration, define the interface you are implementing. A single class may implement more than one interface.

The following examples show how to specify that the IAccount, ICustomer, and IPortfolio interfaces be implemented:

 

// C#
public class BusinessAccount : IAccount, ICustomer, IPortfolio
{
   // Code to implement class here.
}
1.	Implement each property and method required by the interface. Examples are shown below:
4.	// C#
5.	bool ICustomer.ChangeAddress(IAddress newAddress)
6.	{
7.	// Appropriate code goes here.
8.	}
9.	void IPortfolio.BuyEquity()
10.	{
11.	// Code to carry out this procedure goes here.
12.	}
13.	public decimal Balance
14.	{
15.	// Appropriate code goes here.
16.	}

Note   In Visual C#, you cannot implement an interface member with a method of a different name, such as you can in Visual Basic .NET using the Implements keyword.

Write any other code you require your class to contain.