Tuesday, March 1, 2011

Interface

Interface is a comunicating media between two mediums. In c# multiple inheritance is not allowed that's why interface are used to fulfil the needs of multiple inheritance. As c# does not support multiple inheritance then it is necessary that the class can inherit the behaviour of more than one class, that's what interface provides us. In multiple inheritance we had a problem that if a class has two base class and both have some same methods then which method to call. Classes can inherit multiple interface.
Interface are contract of rules that a class which inherits it must follow(i.e must implement the method which are defined in interface). Interface contains method that do not contain any implementation just contain declaration of that method and the class which inherits it must implement those method. Interfaces can contain properties, indexers, and events but interface cannot contains field and interface cannot be instantiate.


Example



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace blog
{
    class Program
    {
        static void Main(string[] args)
        {
            circle objc = new circle();
            objc.fill();
            square objs = new square();
            objs.fill();
            line objl = new line();
            objl.draw();
            Console.ReadKey();
        }
    }
    interface fill
    {
        void fill();
    }
    class shapes  {
        public void draw()  {
            Console.WriteLine("shape Draw");
        }
    }
    class circle : shapes,fill    {
        public void fill()        {
            Console.WriteLine("Circle Fill");
        }
    }
    class square : shapes, fill    {
        public void fill()        {
            Console.WriteLine("Square Fill");
        }
    }
    class line : shapes    {
    }
}