blog

Home / DeveloperSection / Blogs / Interface in C#.Net

Interface in C#.Net

AVADHESH PATEL 3886 10-Jul-2012

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.


c# c# 
Updated 18-Sep-2014
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By