Tuesday, 30 January 2007

Interfaces

Interfaces define a contract (common set of methods that all classes that implement the interface must provide). For example IComparable interface defines the CompareTo method, allowing two instances of a class to be compared for equality.

An interface contains only signatures of methods, delegates or events. The implementation of the methods is done in the classes that implement the interface. An interface can be a member of a namespace or a class and can contain signatures of the following members: Methods, Properties, Indexers & Events.

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.


interface IControl
{
void
Paint();
}
interface
ISurface
{
void
Paint();
}

class
SampleClass : IControl, ISurface
{
public void
Paint()
{
}
}
Both IControl & ISurface will point to the same implementation this cause problems if the implementation needs to be different for each of the interfaces. You can explicitly define the interface implementation if this is the case. This method can only be called through the interface and is accomplished by naming the class member with the name of the interface and a period.

class SampleClass : IControl, ISurface
{
public void
IControl.Paint()
{
}
public void
ISurface.Paint()
{
}
}

2 comments:

Unknown said...

A C# interface differs from a Java interface in that it can't contain fields.

Developer Dave said...

Within Java it is also possible to specify the access specifier and are able to specify contstant values as public, static or final. Declaring the access specifier in C# is unallowed and an error to do so and you are also unable to declare constants in an interface in C# only events, indexers, methods & properties.