Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using Interface?

Tags:

c#

.net

oop

What is the use of using Interface?

I heard that it is used instead of multiple inheritance and data-hiding can also be done with it.

Is there any other advantage, where are the places interface is used, and how can a programmer identify that interface is needed?

What is the difference between explicit interface implementation and implicit interface implementation?

like image 946
Nighil Avatar asked Jan 21 '23 00:01

Nighil


2 Answers

To tackle the implicit/explicit question, let's say that two different interfaces have the same declaration:

interface IBiographicalData

    {
       string LastName
       {
          get;
          set;
       }

    }

    interface ICustomReportData
    {
       string LastName
       {
          get;
          set;
       }
    }

And you have a class implementing both interfaces:

class Person : IBiographicalData, ICustomReportData
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
}

Class Person Implicitly implements both interface because you get the same output with the following code:

Person p = new p();
IBiographicalData iBio = (IBiographicalData)p;
ICustomReportData iCr = (ICustomReportData)p;

Console.WriteLine(p.LastName);
Console.WriteLine(iBio.LastName);
Console.WriteLine(iCr.LastName);

However, to explicitly implement, you can modify the Person class like so:

class Person : IBiographicalData, ICustomReportData
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public string ICustomReportData.LastName
    {
        get { return "Last Name:" + lastName; }
        set { lastName = value; }
    }
}

Now the code:

Console.WriteLine(iCr.LastName);

Will be prefixed with "Last Name:".

http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx

like image 59
ray Avatar answered Jan 30 '23 16:01

ray


Interfaces are very useful for

  • Dependency Injection
  • Inversion of Control
  • Test Isolation
like image 36
StuperUser Avatar answered Jan 30 '23 18:01

StuperUser