The main purpose of "Dot Net Labs" provide the dot net program. You can learn dot net, .Net Core, C#, SQL, Linq step-by-step.

Sunday, 3 July 2016

Interface in c# with simple example


Hello friends, we will learn about interface in c#. An interface is declared using the keyword interface. The interface contains only abstract members, just like the classes interface also contains properties, methods, delegates, or events, but an only declaration, no implementations. An interface cannot be instantiated but can only be inherited by classes or other interfaces.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    interface first
    {
        void hi();
        void hello();
    }
    class Test : first
    {
        public void hi()
        {
            Console.WriteLine("THis is first hi method");
        }
        public void hello()
        {
            Console.WriteLine("THis is first hello method");
        }
        public void bye()
        {
            Console.WriteLine("THis is  bye method");
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            first f = new Test();
            f.hi();
            f.hello();
            Test t1 = new Test();
            t1.bye();

        }
    }

}




There are two types of implementation of interfaces.
    • Implicit interface implementation
    • Explicit interface implementation

Example: The following is an example of Implicit interface implementation.

interface IEmployee

{

    void GetEmployee();

}

 

class Class1 : IEmployee

{

   

    public void GetEmployee()

    {

        Console.WriteLine("Implicit interface implementation.");

    }

 }

 

class Program

{

    static void Main(string[] args)

    {

        Class1 objClass1 = new Class1();

        objClass1.GetEmployee();

    }

}



Example: The following is an example of Explicit interface implementation.

interface IEmployee

{

    void GetEmployee();

}


interface IEmployee2

{

    void GetEmployee();

}


class Class1 : IEmployee, IEmployee2

{

  

    void IEmployee.GetEmployee()

    {

        Console.WriteLine("IEmployee Explicit interface inplementaion.");

    }


    void IEmployee2.GetEmployee()

    {

        Console.WriteLine("IEmployee2 Explicit interface inplementaion.");

    }

}

 

class Program

{

    static void Main(string[] args)

    {

          //Type 1

        Class1 objClass1 = new Class1();

        ((IEmployee)objClass1).GetEmployee();

        ((IEmployee2 )objClass1).GetEmployee();


        //Type 2

        

        IEmployee obj = new Class1();

        obj.GetEmployee();


         IEmployee2 obj = new Class1();

        obj.GetEmployee();


    }

}

0 comments:

Post a Comment

Do not enter spam link

Popular Posts