An interface contains only the signatures of methods, delegates or events. An interface looks like a class, but has no implementation. The only thing it contains is declarations of events, indexers, methods and/or properties. Interfaces in C # provide a way to achieve runtime polymorphism.

Why Use Interfaces?

To allows a class to inherit multiple behaviors from multiple interfaces.

To avoid name ambiguity between the methods of the different classes as was in the use of multiple inheritances in C++.

To combine two or more interfaces such that a class need only implement the combined result. The example code for this is provided as a source file to be downloaded.

To allows Name hiding: Name hiding is the ability to hide an inherited member name from any code outside the derived class.

Defining an Interface
interface IMyInterface
{ void MethodToImplement();
}
{ void MethodToImplement();
}

Implementation of Interface

class InterfaceImplementer : IMyInterface
{ static void Main()
{
InterfaceImplementer iImp =new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
{ static void Main()
{
InterfaceImplementer iImp =new InterfaceImplementer();
iImp.MethodToImplement();
} public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
{
static void Main()
{
InterfaceImplementer iImp =new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
{
static void Main()
{
InterfaceImplementer iImp =new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
{
static void Main()
{
InterfaceImplementer iImp =new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}

Compile example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @interface
{
    interface IMyInterface
    {
        void MethodToImplement();
    }
       class InterfaceImplementer : IMyInterface
    {
        static void Main()
        {
            InterfaceImplementer iImp = new InterfaceImplementer();
            iImp.MethodToImplement();
            Console.ReadLine();
        }
        public void MethodToImplement()
        {
            Console.WriteLine("MethodToImplement() called.");
        }
    }
}

Output:

MethodToImplement() called.

  Modified On Sep-18-2014 01:24:03 PM

Leave Comment