Interfaces in C#

in
Average rating
(0 votes)

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:

interface IExampleInterface
{
void ExampleMethod();
}

class ImplementationClass : IExampleInterface
{
// Explicit interface member implementation:
void IExampleInterface.ExampleMethod()
{
// Method implementation.
}

static void Main()
{
// Declare an interface instance.
IExampleInterface obj = new ImplementationClass();

// Call the member.
obj.ExampleMethod();
}
}

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

Here is an example of Interface Implementation

using System;
interface IPointer
{
// Property signatures:
int x
{
get;
set;
}

int y
{
get;
set;
}
}

class Pointer : IPointer
{
// Fields:
private int _x;
private int _y;

// Constructor:
public Pointer(int x, int y)
{
_x = x;
_y = y;
}

// Property implementation:
public int x
{
get
{
return _x;
}

set
{
_x = value;
}
}

public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}

class MainClass
{
static void PrintPointer(IPointer p)
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}

static void Main()
{
Pointer p = new Pointer(2, 3);
Console.Write("My Pointer: ");
PrintPointer(p);
}
}

Reference:
http://msdn.microsoft.com/en-us/library/87d83y5b(VS.80).aspx