C# > Interfaces

Interfaces in C#

How to use Interfaces in c#?


Interfaces

An interface is similar to the class but it provides a specification rather than a implementation for its members, Interface members are implicity abstract, Class can provide both abstract members and concrete members with implementation, Interface declaration is like class declaration but it provides no implementation for its members since they all are implicitly abstract. An interface contains methods, properties , events and indexers.

Why to use interfaces

Interfaces are used because

  • It does not support multiple inheritance that's why we use interfaces in c#. 
  • Interfaces are better in situations in which you do not have to inherit implementation from a base class.

Advantages of interfaces

The advantages of interfaces are

  • To define the particular methods and properties.
  • To specify the methods and properties with out knowing the derived class.

The declaration of interface

interface Myinterface
{
    void MyMethod();
}

In the above code snippet we have declared interface. We have taken interface as Myinterface and abstract method as MyMethod. This method will be implemented by the classes or structs.


Defining the declaration of the interface

class Myclass : MyInterface
{
    public void MyMethod()
    {
        Console.WriteLine("This is implemented function");
    }
}


In the above code snippet we have declared the MyInterface to Myclass. Interface is named after the letter I as iExample.

Difference between Class versus Interfaces

Interfaces are similar to the classes. which contains properties and methods.

  • In an interface class can inherit multiple interfaces and in the class it defines only single class.  
  • Structs implements interfaces. Classes implements interfaces.  

    

Simple Example program on using interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
interface Iexample
{
    int Add(int a, int b);
    int Mul(int a, int b);
}

class Test : Iexample
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Mul(int a, int b)
    {
        return a * b;
    }

}

class Program
{
    static void Main(string[] args)
    {
        Test obj = new Test();
        Iexample iadd = (Iexample)obj;

        int add = iadd.Add(2, 2);

        int mul = iadd.Mul(2, 8);

        Console.WriteLine(" Addition : {0} ",add);
        Console.WriteLine(" Multiplication : {1} ", add, mul);
        Console.ReadLine();

    }
}

In the above code snippet we have declared the interface. We have defined interface as Iexample and we have taken interface as  int Add(int a, int b); and int Mul(int a, int b); as we are performing the addition and multiplication of the values in the interface We had defined the class Test as Iexample, We have the public int Add(int a, int b) return a + b; } and public int Mul(int a, int b) return a * b; } which performs the addition and multiplication operation in the interface. We have taken class as  program and in the main function of the program we have declared Test obj = new Test(); and Iexample iadd = (Iexample)obj; We had defined object to the interface values and we are giving the values as 2,2 for (addition) and 2,8 for (multiplication) of the values and the console.Writeline prints the values as add and multiplication of the values in the output.

output

 


Multiple interfaces

Classes and structs can use not only single interface but they can also use multiple interfaces.

Declaring multiple interfaces

interface Iaddition
{
    void one();
}

Another interface is as

interface Imultiplication
{
    void Two();
}

 We can implement two interfaces using single class

class MyClass : Iaddition, Imultiplication 
{
    
    public void One()
    {
        .........;
    }
    
    public void Two()
    {
        .........;
    }
}

In the above code snippet we have defined how to use multiple interfaces in a single class. We are having two interfaces Ifirst and Isecond. We are assigning two interfaces in the main function of class Myclass.    


Example program on Multiple interface

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

interface Isoftware
{
    void Hello();
}

interface IHardware
{
    void Hello();
}

class Test : Isoftware, IHardware
{
    void Isoftware.Hello()
    {
        Console.WriteLine("This is Software industry");
    }

    void IHardware.Hello()
    {
        Console.WriteLine("This is complete Hardware");
    }
}

public class interfacetest
{
    public static void Main()
    {
        Isoftware Obj1 = new Test();
        Obj1.Hello();

        IHardware Obj2 = new Test();
        Obj2.Hello();
    }
}

In the above code snippet we have defined how to use multiple interfaces. We have taken interfaces as Isoftware and IHardware as multiple interfaces and in the Isoftware we have void Hello function and in the IHardware we have void Hello function, We have taken class as testclass and declaring the multiple interfaces as Isoftware and IHardware to the class test. In the void function of Isoftware we are declaring the console.writeline as This is sofware industry and in the void function of IHardware we are declaring the console.Writeline as This is complete Hardware industry. In the mainfunction of the program we are declaring the program as interface test and in the main function we have created an obj1 to the Isoftware as new Test and obj1.Hello calls the interface Software  and we are creating the obj2 to IHardware as newtest and obj2.Hello calls the interface IHardware and prints the values in the output.


Output

          


Explicit Interface

Implementing multiple interfaces can sometimes result in collisions between member signatures. We can resolve such collisions by using Explicit interface.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Explicit
{
    class Program
    {
        interface techfunda              
        {
            void Test();
        }

        interface dotnetfunda              
        {
            void Test();
        }

        class MyClass : techfunda, dotnetfunda  
        {
            public void Test()
            {
                Console.WriteLine("This is techfunda website");
            }

            void dotnetfunda.Test()             
            {
                Console.WriteLine("This is dotnetfunda website");
            }
        }

        static void Main()
        {
            MyClass my = new MyClass();
            my.Test();                  

            ((dotnetfunda)my).Test();     
        }
    }
}

In the above code snippet we have defined how to use explicit interface. we have taken two interfaces  as techfunda and dotnetfunda. we have the function void test in the techfunda and we are having the void testfunction in dotnetfunda we have declared myclass as dotnetfunda and techfunda. In the void test function we are calling the interface techfunda as in the console writeline prints This is techfunda website and the void dotnetfunda.Test prints the value as it is explicit interface.  which calls the interface dotnetfunda and prints the value as This is dotnetfunda website. In the main function of the program we are having Myclass as my which is equal to new myclass and my.test calls the interface as techfunda and dotnetfunda.my.test calls the function dotnetfunda which is explicit interface.

output


Virtual implementation of the interfaces

An implicit interface is sealed by default, In order to override it must be called with virtual or abstract.

Example program on using virtual interfaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    interface Icsharp
    {
        void Start();
    }

    class First : Icsharp
    {
        public virtual void Start()
        {
            Console.WriteLine("It is Base class");
        }
    }
    class Second : First
    {
        public override void Start()
        {
            Console.WriteLine("It is from class second");
        }
    }

    static void Main()
    {
        Second member = new Second();
        member.Start();

        ((First)member).Start();
        ((Icsharp)member).Start();
    }
}

In the above code snippet we have declared how to use virtual interfaces.  we have taken class as program and we are declaring the inerface as Icsharp and we are having the function void start in the interface Icsharp.  we are declaring class First and class second, in the class first we are having the virtual start function as the console.Writeline prints the value as it is base class and the class second we are assigning the value as first and in  the function we are having the override function in the second which is having the console.Writeline as it is from derived class and in the main function of the class program we are declaring the second as member =new second and member.start calls the function of class second  and in the nextline we are having the function as ((first)member).start() which is assigned to class second and in the nextline we are having the ((Icsharp)member).start() which calls the function of first and first is assigned to the class second  as it calls the class second and prints the output values from class second.          


output


Reimplementing Explicit Interfaces

Re-implementing means re-using the interface in the derived classes even though it is already implemented by the base class. When we call through the interface, It checks whether the member in a base class is virtual or not. It also checks whether the implementation of a member is implicit or explicit

Example program on reimplementing the explicit interfaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
    {
        interface ITutorial
        {
            void Start();
        }

        class one : ITutorial
        {
            void ITutorial.Start()
            {
                Console.WriteLine("It is First.Start");
            }
        }

        class Two : one, ITutorial
        {
            public new void Start()
            {
                Console.WriteLine("It is Second.Start");
            }
        }

        static void Main()
        {
            Two file = new Two();
            file.Start();
            ((ITutorial)file).Start();
        }
    }
In the above code snippet we are defining how to use reimplementation of interfaces. We have taken Interface as ITutorial, We have given function as void start in the interface Itutorial and we have defined two classes  as class one and class two. In class one we have defined as Itutorial, in this class we have explicit function as void ITutorial.start() and it calls the console.writeline as It is first and in the class two we have defined it as one and Itutorial, The void function calls the console.Writeline as It is second start and in the main function of the program we have defined Class Two as file and assigned it to new Two and file.start() prints the value in the output, ((Itutorial) file).start() prints the value as It is second.Start.
            

output

Reimplementing implicit interface

Re-implementing means re-using the interface in the derived classes even though it is already implemented by the base class. When we call through the interface, It checks whether the member in a base class is virtual or not. It also checks whether the implementation of a member is implicit or explicit

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
    {
        interface IExample                 
        {
            void Start();
        }

        class First : IExample
        {
            public void Start()          
            {
                Console.WriteLine("This is IExample's First.Start");
            }
        }

        class Second : First, IExample
        {
            public new void Start()
            {
                Console.WriteLine("This is Second.Start");
            }
        }

        static void Main()
        {
            Second app = new Second();
            app.Start();                   
            ((IExample)app).Start();       
            ((First)app).Start();          
        }
    }

In the above code, we have an interface IExample. We cannot mark virtual to the base class method as we are using implicit interface implementation IExample.Start() to the base class (First) method. Now, re-implementing comes into the picture. In order to override the base class (First) method, we have to re-implement IExample's Start() method at the derived class (Second) like we did in the above code. This will let the object app to call the derived class's implementation even we use interface casting.

output

 Views: 5608 | Post Order: 16



Write for us






Hosting Recommendations