Wednesday 10 September 2014

Interface in C# with example

Interface: 

Mainly Interface used in C# for achieving multiple inheritance. As .net does not support multiple inheritance.
In interface we define methods and we will implement in derived classes.

  • An interface cannot inherit from a class. 
  • An interface can inherit from multiple interfaces. 
  • A class can inherit from multiple interfaces, but only one class. 
  • Interface members must be methods, properties, events, or indexers. 
  • All interface members must have public access (the default). 
  • By convention, an interface name should begin with an uppercase I.


Example:
using System;
interface inter1
{
    void greet();
}

interface inter2 : inter1
{
    void display();
}

interface inter3 : inter2
{
    void show();
}

class demo : inter3
{
    public void greet()
    {
        Console.WriteLine("Method from inter1");
    }
    public void display()
    {
        Console.WriteLine("Method from inter2");
    }
    public void show()
    {
        Console.WriteLine("Method from inter3");
    }

    public static void Main()
    {
        inter3 i = new demo();
        i.greet(); i.display(); i.show();
    }

}

0 comments:

Post a Comment