Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of Interfaces C#

Tags:

c#

interface

I would like to know the significant use of Interface. I have read many articles but not getting clearly the concept of interface.

I have written a small program. I have defined the Interface Itest.Class(Manager) has implemented the Interface.Another class(Employee) has not implemented interface. But defined the same method(DoSomething()) in the interface in the class(Employee). I can call the method from the class object. Then why should i go and implement interface. I can directly implement the method in a class and call the method. Why should i go for extra step of implementing method in a Interface and then inheriting the interface by class. I know interface supports multiple inheritance, but I am not using multiple inheritance in this example.

Thanks for any ideas or input.

public interface Itest
{
    void DoSomething();
}

public class Manager:Itest
{
    public void DoSomething()
    {
        Console.WriteLine("test....");
    }

}
class Employee
{
    public void DoSomething()
    {
        Console.WriteLine("test....");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Manager m = new Manager();
        m.DoSomething();
        Employee e = new Employee();
        e.DoSomething();
        Console.ReadLine();
    }
}
like image 712
Shikha Avatar asked Feb 08 '10 10:02

Shikha


3 Answers

Interfaces allow you to sort of use multiple inheritance. In your example, it woulda allow you to put an instance of Employee or Manager into the same variable, and then call DoSomething on that variable, with the method call being dispatched to the instance that is currently referenced by that variable. For example:

public interface IEmployee {
    void DoSomething();
}
// assume Manager and Employee both implement IEmployee

IEmployee ie = new Manager();
ie.DoSomething();    // calls Manager.DoSomething()
ie = new Employee();
ie.DoSomething();    // calls Employee.DoSomething()

If you didn't use interfaces, you would have to do:

object o;

// assign Manager or Employee (or something else!) to o

if (o is Manager)
    ((Manager)o).DoSomething();
else if (o is Employee)
    ((Employee)o).DoSomething();

An interface defines a contract, and as long as an instance implements that interface you don't care what it actually is at runtime. You can have the same class implement multiple interfaces, and then use instances of that class in all variables of those interfaces. You couldn't use the same for abstract classes, as a class can only inherit off one class at a time.

One example where I'm using interfaces now is to define an object model - I've got interfaces for various properties (IHasStorage, IHasPrivileges, IHasCheezburger), then the classes representing the concrete objects implement whichever and however many interfaces are appropriate for that class' properties

like image 169
thecoop Avatar answered Sep 17 '22 12:09

thecoop


Interfaces are used for abstraction (abstract classes are also used for this, but normally contain some implementation that is intended for reuse).

In C# they allow the use of multiple inheritance, meaning you can implement many different interfaces in one class.

If you have many different implementations of an interface, you can substitute them for one another, so long as you use the interface declaration.

For example:

IAnimal can be implemented by Cat and by Dog. In other code, you want to call the Talk method that is declared in the interface. Your code does not have to care whether it is a Cat object or a Dog object. You can add a Duck or a Human and not change that piece of code.

This is also useful when testing your code with mock objects, so a simple object can be substituted for the real one for testing purposes.

Some interfaces are used as markers so reflection can pick them up easily (on example is the ISerializable interface, marking a class as serializable).

like image 27
Oded Avatar answered Sep 17 '22 12:09

Oded


Implementation inheritance models an "IS A KIND OF" relationship, whilst interface inheritance models a "CAN BEHAVE LIKE" relationship. It's no coincidence that many of the BCL interface names end with "-able", representing the ability to do something. To demonstrate, image the following code:

class Person
{
  public string Name{get;set;}
  public void Walk() {/*code elided*/}
}

class Employee : Person
{
  public int Id{get;private set;}
}

Clearly, an Employee "is a kind of" Person. All employees are people, therefore they all have a Name and can Walk(). By all means make Person or Employee abstract, it doesn't change the fact that all employees are people.

Now let's get a bit more abstract and talk about the concept of being a vehicle. The absolute essential for a thing to be a vehicle is that it must be able to move and stop. You might include steering and carrying passengers but I'm keeping it very abstract.

Let's think about some things that are vehicles. A car, of course, but how about a person? They can move and stop (and when I give my nephews and nieces piggy-backs I'm carrying passengers too!) A wheely chair? I'm forever davrossing around the office. I'm a keen sailor too, and use the wind to accelerate and decelerate my vehicle.

You can't model this kind of a relationship using implementation inheritance, because you have lots of different things that "can act like" a vehicle but don't neccessarily inherit from the same base class.

A pogostick (with apologies to professional pogo-ers) IS A KIND OF Toy, but CAN ACT AS a vehicle. Not all toys are vehicles. A Person has no relationship to a Car, other than the fact that it CAN ACT AS a vehicle.

interface IVehicle
{
  void Move();
  void Stop();
}

class Toy{}

class PogoStick : Toy, IVehicle
{
  public void Move(){ /* boing boing */}
  public void Stop(){ /* fall over */}
}

class Car: IVehicle
{
  public void Move(){ /* vroom vroom */}
  public void Stop(){ /* <screeeech!> */}
}

class Person : IVehicle
{
  public string Name{get;set;}
  public void Walk() {/*code elided*/}
  void IVehicle.Move() { Walk(); }
  void IVehicle.Stop() { /*whatever!*/}
}

class Program
{
  static void Main()
  {
    IVehicle[] vehicles = new IVehicle[3];
    vehicles[0] = new PogoStick();
    vehicles[1] = new Car();
    vehicles[2] = new Employee(); //implements IVehicle because it IS A KIND OF Person

    vehicles.ForEach(v => v.Move());

    //it's worth pointing out that
    vehicles[2].Stop();
    //works fine, but
    Person p = new Person();
    p.Move();
    //won't, as I explicitly implemented the interface, meaning I can only get at the
    //methods via a reference to the interface, not to the implementing class.
  }
}

To use an example from .NET itself, what on Earth does a string have in common with a List? Not a lot, except that I can "foreach" both of them:

class Demo
{
  static void Main()
  {
    string s = "Hello!";
    List<Employee> payroll = new List<Employee>();

    for each (var item in s)
    {
      Console.WriteLine(item);
    }

    for each (var item in payroll)
    {
      Console.WriteLine(item);
    }
}

The common base class for string and List is object, but not all objects are "for-each-able", so there has to be something else going on. Namely that they both implement the IEnumerable interface (there's that -able!)

like image 22
Daniel Ives Avatar answered Sep 17 '22 12:09

Daniel Ives