123

I am aware that this is a very basic question, but an interviewer asked me in a very trick way and I was helpless :(

I know only material or theoretical definition for an interface and also implemented it in many projects I worked on. But I really don't understand why and how is this useful.

I also don't understand one thing in interface. i.e for example, we use

conn.Dispose(); in finally block. But I don't see that class is implementing or inheriting IDisposable interface (SqlConnection) class I mean. I am wondering how I can just call the method name. Also in the same thing, I am not understanding how Dispose method works as because, we need to implement the function body with our own implementation for all interface methods. So how Interfaces are accepted or named as contracts? These questions kept on rolling in my mind till now and frankly I never saw any good thread that would explain my questions in a way that I can understand.

MSDN as usual looks very scary and no single line is clear there (Folks, kindly excuse who are into high level development, I strongly feel that any code or article should reach the mind of anyone who see it, hence like many others say, MSDN is not of use).

The interviewer said:

He has 5 methods and he is happy to implement it in the class directly, but if you have to go for Abstract class or interface, which one you choose and why ? I did answered him all the stuffs that I read in various blog saying advantage and disadvantage of both abstract class and interface, but he is not convinced, he is trying to understand "Why Interface" in general. "Why abstract class" in general even if I can implement the same methods only one time and not gona change it.

I see no where in net, I could get an article that would explain me clearly about interfaces and its functioning. I am one of those many programmers, who still dont know about interfaces (I know theoretical and methods I used) but not satisfied that I understood it clearly.

9
  • 5
    Interfaces are one I have struggled to understand also. Good question.
    – Brian
    Jun 6, 2012 at 13:07
  • 4
    programming to an abstract contract rather than a concrete implementation....In short, it means you can substitute any object that implements an interface when an interface is required. Jun 6, 2012 at 13:08
  • 7
    SqlConnection inherits System.ComponentModel.Component which implements IDisposable.
    – Lee
    Jun 6, 2012 at 13:10
  • 2
    @MitchWheat - It's not meant to be an example, the question asks how SqlConnection implements IDisposable.
    – Lee
    Jun 6, 2012 at 13:12
  • Oh Lee, that made me understand thank you. But I still don't see how or where "Dispose" method functionality is defined.
    – Jasmine
    Jun 6, 2012 at 13:12

16 Answers 16

94

Interfaces are excellent when you want to create something like it:

using System;

namespace MyInterfaceExample
{
    public interface IMyLogInterface
    {
        //I want to have a specific method that I'll use in MyLogClass
        void WriteLog();       
    }

    public class MyClass : IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyClass was Logged");
        }
    }

    public class MyOtherClass : IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyOtherClass was Logged");
            Console.Write("And I Logged it different, than MyClass");
        }
    }

    public class MyLogClass
    {
        //I created a WriteLog method where I can pass as a parameter any object that implements IMyLogInterface.
        public static void WriteLog(IMyLogInterface myLogObject)
        {
            myLogObject.WriteLog(); //So I can use WriteLog here.
        }
    }

    public class MyMainClass
    {
        public void DoSomething()
        {
            MyClass aClass = new MyClass();
            MyOtherClass otherClass = new MyOtherClass();

            MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation
            MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log.
        }
    }
}

In my example, I could be a developer who writes MyLogClass, and the other developers, could create their classes, and when they wanted to log, they implement the interface IMyLogInterface. It is as they were asking me what they need to implement to use WriteLog() method in MyLogClass. The answer they will find in the interface.

7
  • 3
    Hey that looks like a very good ingredient for me to understand, I really appreciate it, thanks a lot :) :)
    – Jasmine
    Jun 6, 2012 at 13:46
  • 14
    My question is if you are instantiating MyClass and MyOtherClass why wouldn't you simply call aClass.WriteLog() why add that extra step. The implementation of WriteLog() would remain different for each of the classes but you already have the object so why pass it to a handler class?
    – Zach M.
    Dec 19, 2014 at 19:09
  • Hm might it be that if you put your logging example on nugget that it would be simpler for others to use your logger, without knowing the details .. but on the other hand, still its not some universal class, (ea i could write an interface with logging AND allert levels) interfaces are still only within your scope. so besides yourself for who is benefiting from it ?.
    – Peter
    Nov 19, 2016 at 11:55
  • 2
    @ZachM. If i am right, The answer means is, he will not instantiate the classes , but other developers will instantiate the classes and pass it as parameter to MyLogClass WriteLog method. So his method can handle any object which implements IMyLogInterface . Here is another interesting post.
    – Shaiju T
    Jul 18, 2017 at 7:57
  • 1
    My question is why Interface??? The above scenario can also be achieved by an abstract class with all abstract methods. Oct 3, 2019 at 11:22
54

One reason I use interfaces is because it increases the flexibility of the code. Let's say we got a method that takes an object of class type Account as parameter, such as:

public void DoSomething(Account account) {
  // Do awesome stuff here.
}

The problem with this, is that the method parameter is fixed towards an implementation of an account. This is fine if you would never need any other type of account. Take this example, which instead uses an account interface as parameter.

public void DoSomething(IAccount account) {
  // Do awesome stuff here.
}

This solution is not fixed towards an implementation, which means that I can pass it a SuperSavingsAccount or a ExclusiveAccount (both implementing the IAccount interface) and get different behavior for each implemented account.

0
49

Interfaces are contracts that implementers must follow. Abstract classes allow contracts plus shared implementations - something that Interfaces cannot have. Classes can implement and inherit multiple interfaces. Classes can only extend a single abstract class.

Why Interface

  • You don't have default or shared code implementation
  • You want to share data contracts (web services, SOA)
  • You have different implementations for each interface implementer (IDbCommand has SqlCommand and OracleCommand which implement the interface in specific ways)
  • You want to support multiple inheritance.

Why Abstract

3
  • 2
    @Silver I read most of what you have typed in blogs, but I am trying to understand practically. I have done WCF services, exposed interfaces (But it was just a single stand alone app with no upstream or downstream). Hence I couldn't understand it properly although I very well designed and implemented interfaces. My question is, practically, you just share the method names contract means right ? HOW IS THIS USEFUL :( I know it just forces to implement all the methods, but else how ? In your post above on interface, 2nd point says share, means can you give a practical real time example of this
    – Jasmine
    Jun 6, 2012 at 13:29
  • 1
    For a practical example regarding interfaces and SOA, we share our WCF Interfaces (DataContracts) in a .NET Assembly (e.g. Contracts.Shared.dll) so that .NET client consumers can easily interoperate using ChannelFactory (avoiding generating code via Add Service Reference, etc.) or using Add Service Reference with Shared Types Jun 6, 2012 at 13:34
  • If, I will declare only abstract methods inside an abstract calss, then the abstract class will act as interface, then why do we need interface? Oct 3, 2019 at 11:24
26

enter image description here

So in this example, the PowerSocket doesn't know anything else about the other objects. The objects all depend on Power provided by the PowerSocket, so they implement IPowerPlug, and in so doing they can connect to it.

Interfaces are useful because they provide contracts that objects can use to work together without needing to know anything else about each other.

2
  • This makes sense, but I am still struggling to understand, could you just not create a base class for PowerSocket and all those other things inherit it if needed. Technically Power Sockets have no idea about the other classes. Oct 16, 2019 at 9:28
  • I think because multiple inheritance is not allowed in C# Jun 29, 2020 at 23:01
23

In one word - because of Polymorphism!

If you "Program to an Interface, not an Implementation" than you can inject different objects which share the same interface(type) into the method as an argument. This way your method code is not coupled with any implementation of another class which means it's always open to work with newly created objects of the same interface. (Open/Close Principle)

  • Look into Dependency Injection and definitely read Design Patterns - Elements of Reusable Object-Oriented Software by GOF.
6

I believe that many blood was already spilled in asking this questions, and many tries to resolve this issues by explaining robot-like terms that no normal human can understand.

So First. to learn why interface and why abstract you need to learn what are them for. I personnaly learned this two when applying Factory Class. you find a good tuturial on this link

Now let's dig-in base on the link I already gave.

You have Vehicle class that might change upon user requirement (like adding Truck, Tank, Airplane, etc. And given we have

public class clsBike:IChoice
{
   #region IChoice Members
    public string Buy()
    {
       return ("You choose Bike");
    }
    #endregion
}

and

public class clsCar:IChoice
{
   #region IChoice Members
    public string Buy()
    {
       return ("You choose Car");
    }
    #endregion
}

and both has Contract IChoice that simply say My Class should have Buy method

public interface IChoice
{
    string Buy();
}

Now, you see, that interface only enforce the method Buy() but let the inherited class decide what to do when they implement it. This is the limitation of Interface, using purely interface, you might end up repeating some task that we can implement automatically using abstact. On our example let say, buying each vehicle has a discount.

public abstract class Choice
{
    public abstract string Discount { get; }
    public abstract string Type { get; }
    public string Buy()
    {
       return "You buy" + Type + " with " + Discount;
}
public class clsBike: Choice
{
    public abstract string Discount { get { return "10% Discount Off"; } }
    public abstract string Type { get { return "Bike"; } }
}

public class clsCar:Choice
{
    public abstract string Discount { get { return " $15K Less"; } }
    public abstract string Type { get { return "Car"; } }
}

Now using the Factory Class, you can achieve the same thing but in using abstract, you let the base class execute the Buy() method.

In Summary : Interface contracts let the inherit class do the implementation while Abstract class Contracts may initialize the implementation (which can override by Inherit class)

4

C# doesn't have duck typing - just because you know a certain method is implemented across a set of concrete classes doesn't mean you can treat them all the same with regards to calling that method. Implementing an interface allows you to treat all classes implementing it as the same type of thing, with regards to what that interface defines.

1
  • 3
    You can get sort of ducktyping in .net4 with the dynamic type. Jun 6, 2012 at 13:30
3

This is an easy example:

Both of Array and List implement the interface IList. Below we have a string[] and a List<string> and manipulate both of them with only one method by using IList:

string[] myArray = { "zero", "one", "two", "three", "four"};
List<string> myList = new List<string>{ "zero", "one", "two", "three"};

//a methode that manipulates both of our collections with IList
static void CheckForDigit(IList collection, string digit)
{
    Console.Write(collection.Contains(digit));  //checks if the collection has a specific digit
    Console.Write("----");
    Console.WriteLine(collection.ToString()); //writes the type of collection
}

static void Main()
{
    CheckForDigit(myArray, "one");   //True----System.String[]
    CheckForDigit(myList, "one");   //True----System.Collections.Generic.List`1[System.String]



//Another test:

    CheckForDigit(myArray, "four");   //True----System.String[]
    CheckForDigit(myList, "four");   //false----System.Collections.Generic.List`1[System.String]
}
2

With an interface you can do the following:

1) Create segregated interfaces which offer differing cuts of your implementation, allowing for a more cohesive interface.

2) Allow for multiple methods with the same name between interfaces, because hey, you have no conflicting implementation, just a signature.

3) You can version and hive off your interface independantly of your implementation, ensuring a contract is met.

4) Your code can rely on abstraction rather than concretion, allowing for smart dependency injection, including injecting test Mocks etc.

There are many more reasons I'm sure, these are just a few.

An abstract class allows you to have a partially concrete base to work from, this is not the same as an interface but has its own qualities such as the ability to create partial implementation using the template method pattern.

1
  • You neglected the most important thing: implementing an interface makes your class usable by any code needing an implementation of that interface, without the code in question having to know anything about your class.
    – supercat
    Apr 16, 2014 at 18:51
2

Interfaces are to make an abstraction (an archetype) of the abstraction (the classes) of the reality (the objects).

Interfaces are to specify contract terms without providing implementation provided by classes.

Interfaces are specifications:

  • Interfaces are design time artifacts to specify the immobile behavior of the concept as it is alone and static.

  • Classes are implementation time artifacts to specify the mobile structure of the reality as it interacts and move.

What is an interface?

When you observe a cat you can say that it is an animal that has four paws, a head, a trunk, a tail and hair. You can see that he can walk, run, eat and meow. And so on.

You have just defined an interface with its properties and its operations. As such you have not defined any modus operandi, but only features and capabilities without knowing how things work: you have defined abilities and distinctions.

As such it is not really yet a class even though in UML we call this a class in a class diagram because we can define privates and protected members to begin having a deep view of the artifact. Do not be confused here because in UML an interface is a slightly different thing that an interface in C#: it is like a partial access point to the abstraction atom. As such we said that a class can implements multiple interfaces. As such it is the same thing, but not, because interfaces in C# are both used to abstract the abstraction and to limit this abstraction as an access point. It's two different uses. Thus a class in UML represents a full coupling interface to a programming class, whereas an UML interface represents a decoupling interface of a section of a programming class. Indeed, the class diagram in UML does not take care of the implementation and all its artifacts are at the programming interface level. While we map UML classes to programming classes, it is a transposition of abstract abstraction into concrete abstraction. There is a subtlety that explains the dichotomy between the field of design and the field of programming. So a class in UML is a programming class from the point of view of a programming interface while considering inner hidden things.

Interfaces also allow to simulate multiple inheritance when not available in an awkward way. For example, the cat class will implement the cat interface that derives itself from the animal interface. This cat class will also implement these interfaces: walk, run, eat and make a sound. This compensates for the absence of multiple inheritance at the class level, but each time you need to reimplement everything and you can not factor the reality at best like the reality itself do it.

To understand that we can refer to Pascal Object coding where you define in a unit the interface and the implementation sections. In the interface you define the types and in the implementation you implement the type:

unit UnitName;

interface

type
  TheClass = class
  public
    procedure TheMethod;
  end;

implementation

class procedure TheClass.TheMethod;
begin
end;

Here, the interface section match to the UML class design while Interfaces types are thus others things.

So in our business we have one word, interface, to nominate two distinct but similar things, and it is a source of confusion.

Also in C# for example, programming interfaces allow to compensate the absence of true generic polymorphism on open types without really succeeding the goal because you lost the strongly-typed hability.

After all, interfaces are necessary to allow incompatible systems to communicate without worrying about the implementation and the management of objects in memory like introduced with the (Distributed) Common Object Model.

What is a class?

After defining a reduction of the reality from an external point of view, you can then describe it from an inside perspective: this is the class where you define data processing and message management to allow the reality you have encapsulated to come to life and interact thanks to objects using instances.

So in UML you realize a fractal immersion in the wheels of the machinery and you describe the states, the interactions and so on to be be able to implement the abstraction of the fragment of the reality you want to handle.

As such, an abstract class is somehow the equivalent of an interface from the point of view of the compiler.

More information

Protocol (object-oriented programming)

C# - Interfaces

C# - Classes

1

You can only inherit from one abstract class. You can inherit from multiple interfaces. This determines what I use for most of the cases.

The advantage of abstract class would be that you can have a base implementation. However, in the case of IDisposable, a default implementation is useless, since the base class does not know how to properly clean things up. Thus, an interface would be more suitable.

1

Both abstract class and interface are contracts.

The idea of a contract is you specify some behavior. If you say you've implemented you've agreed to the contract.

The choice of abstract over interrface is.

Any non abstract descendant of the abstract class will implement the contract.

versus

Any class that implements the interface will implement the contract.

So you use abstract when you want to specify some behavior all descendants must implement and save yourself defining a separate interface, but now everything that meets this effectively aggregated contract must be a descendant.

1

Let me tell you about flying toasters.

flying toaster

There are, of course, many situations where you can build a working software system without declaring or implementing any interfaces at all: any object-oriented software design can be realized using nothing but classes.

Then again, any software system can also be implemented in Assembly Language, or better yet in Machine Code. The reason why we use abstraction mechanisms is because they tend to make things easier. Interfaces are such an abstraction mechanism.

So, it just so happens that there are certain non-trivial object-oriented designs which are so much easier to implement if you use interfaces, that interfaces practically become necessary in those cases.

These non-trivial designs have to do with multiple inheritance, which, in its "true" form, is when a class inherits not from just one base class, but from two or more base classes. This true form is not possible in C#, but before languages like C# and Java came into existence, the language that ruled was C++, which fully supports true multiple inheritance. Unfortunately, true multiple inheritance turned out to not be a very good idea, because it immensely complicates the design of the language, and it also gives rise to various problems, for example the famous "Diamond Problem". (See "What is the exact problem with multiple inheritance?" answer by J Francis)

So, if someone wanted to build a "flying toaster" class, they would inherit from some existing "toaster" class and also from some existing "flying" class. The kind of problem they were likely to run into was that the power supply of the toaster class was likely to be a wall socket, while the power supply of the flying machine class was likely to be pigeon food, and the resulting new class would either somehow have both, or it would be unclear which one it would have. (The Diamond Problem.)

The creators of languages like C# and Java decided to not allow true multiple inheritance, in order to keep the language simple and to avoid pitfalls like the Diamond Problem. However, some form of multiple inheritance is still necessary, (or at least very highly desirable,) so in these languages they introduced interfaces as a means of supporting a lesser form of multiple inheritance while avoiding the problems and the complexity of true multiple inheritance.

In this lesser form of multiple inheritance, you are not allowed to have a class which inherits from more than one base class, but you can at least inherit from one or more interfaces. So, if you want to build a flying toaster, you cannot inherit both from some existing toaster class and some existing flying class, but what you can do is inherit from an existing toaster class and then also expose a flying interface which you implement yourself, possibly using whatever means you have already inherited from toaster.

So, unless you ever feel the need to create a class which aggregates two different and unrelated sets of functionality, you are not going to need any form of multiple inheritance, so you are not going to need to declare, or implement, any interfaces.

0

Interfaces allow the class designer to make the available methods very clear for the end user. They are also an integral part of polymorphism.

1
  • Well said on your 1st statement. But I dint understand your 2nd statement, could you please elaborate with a real time example please ?
    – Jasmine
    Jun 6, 2012 at 13:31
0

I won't post the definition of an interface against an abstract class because I think you know very well the theory and I assume you know the SOLID principles so let's get practical.

As you know interfaces cannot have any code so the dis-vantage are quite simple to understand.

if you need to initialize the property of your class providing a constructor or you want to provide part of the implementation an abstract class would be a good fit against an interface which would not allow you to do that.

So in very general you should prefer abstract class to interfaces when you need to provide a constructor or any code to the client which will inherit/extend your class

-2

Abstract class are crated for related entities where as Interfaces can be used for unrelated entities.

For e.g if I have two entities say Animal and Human then i will go for Interface where as if i have to go in detail say Tiger,lion and want to relate with Animal then will choose Animal Abstract class..

will look like below

   Interface             
   ____|____
  |        |
Animal   Human



  Animal (Abstract class)
   __|___
  |      |
Tiger   Lion

Not the answer you're looking for? Browse other questions tagged or ask your own question.