Home > DeveloperSection > Blogs > Interface

Interface


C# C# 
Ratings:
0 Comment(s)
 1320  View(s)
Rate this:

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

{

    interface IMessage // create interface using interface keyword

    {

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

        void showMessage();

    }

    class InterfaceDemoImplementation : IMessage // implement interface

    {

        string getStringMessage;  //declare variable for getting message

      

 public void getMessage(string msg)  //interface method must override

        {

            getStringMessage = msg;

        }

      

 public void showMessage()           //interface method

        {

            Console.WriteLine(getStringMessage);

        }

    }

    class Demo

    {

        static void Main(string[] args)

        {

 

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

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

      interfaceDemo.showMessage();

      Console.ReadKey();

        }

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick