C Sharp Programming/Interfaces
From Wikibooks, the open-content textbooks collection
An interface in C# is type definition similar to a class except that it purely represents a contract between an object and a user of the object. An interface cannot be directly instantiated as an object. No data members can be defined in an interface. Methods and properties can only be declared, not defined. For example, the following defines a simple interface:
interface IShape
{
void Draw();
double X { get; set; }
double Y { get; set; }
}
A convention used in the .NET Framework (and likewise by many C# programmers) is to place an "I" at the beginning of an interface name to distinguish it from a class name. Another common interface naming convention is used when an interface declares only one key method, such Draw() in the above example. The interface name is then formed by adding the suffix "able" to the method name. So, in the above example, the interface name would be IDrawable. This convention is also used throughout the .NET Framework.
Implementing an interface is simply done by inheriting off the interface and then defining all the methods and properties declared by the interface. For example:
class Square : IShape
{
private double mX, mY;
public void Draw() { ... }
public double X
{
set { mX = value; }
get { return mX; }
}
public double Y
{
set { mY = value; }
get { return mY; }
}
}
Although a class can only inherit from one other class, it can inherit from any number of interfaces. This is simplified form of multiple inheritance supported by C#. When inheriting from a class and one or more interfaces, the base class should be provided first in the inheritance list followed by any interfaces to be implemented. For example:
class MyClass : Class1, Interface1, Interface2 { ... }
Object references can be declared using an interface type. For example, using the previous examples:
class MyClass
{
static void Main()
{
IShape shape = new Square();
shape.Draw();
}
}
Interfaces can inherit off of any number of other interfaces but cannot inherit from classes. For example:
interface IRotateable
{
void Rotate(double theta);
}
interface IDrawable : IRotateable
{
void Draw();
}
[edit] Additional Details
Access specifiers (i.e. private, internal, etc) cannot be provided for interface members. All members are public. A class implementing an interface must define all the members declared by the interface as public. The implementing class has the option of making an implemented method virtual if it is expected to be overridden in a child class.
There are no static methods within an interface. Any static methods can be implemented in a class that manages objects using that interface.
In addition to methods and properties, interfaces can declare events and indexers as well.