blog

Home / DeveloperSection / Blogs / Interface

Interface

Anchal Kesharwani2935 12-Aug-2014

Interface

In this blog I’m explaining Interface.

An interface looks like a class, but has no implementation. The only thing it contains are declarations of events, indexers, methods and/or properties. The reason interfaces only provide declarations is because they are inherited by classes and structures, which must provide an implementation for each interface member declared Interfaces in C # provide a way to achieve runtime polymorphism or provide overridden property of polymorphism. Interface allow to derived class it must be override with same signature and parameter. Interfaces are a powerful programming tool because they let you separate the definition of objects from their implementation.

Benefits of Interface

·         Interfaces are better than base classes because you can define a single implementation that can implement multiple interfaces.

·         Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

·         This two classes has the same function name with different body.

·         Interfaces are better in situations in which you do not have to inherit implementation from a base class.

·        

Example

using System;

namespace InterfaceDemo

{

    interfaceIMessage// create interface using interface keyword

    {

        void getMessage(string msg); // declare a method for get Message

        void showMessage();

    }

    classInterfaceDemoImplementation : IMessage// implement interface

    {

        string getStringMessage;  //declare variable for getting message

      

 publicvoid getMessage(string msg)  //interface method must override

        {

            getStringMessage = msg;

        }

      

 publicvoid showMessage()           //interface method

        {

            Console.WriteLine(getStringMessage);

        }

    }

    classDemo

    {

        staticvoid Main(string[] args)

        {

 

InterfaceDemoImplementation interfaceDemo = newInterfaceDemoImplementation(); // create instance of InterfaceDemoImplementation & use the interface

      interfaceDemo.getMessage("This Demo for understand Interface");

      interfaceDemo.showMessage();

      Console.ReadKey();

        }

    }

}


Updated 18-Sep-2014

Leave Comment

Comments

Liked By