1

We define interface as below:

interface IMyInterface
{
    void MethodToImplement();
}

And impliments as below:

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

instead of creating a interface , why can we use the function directly like below :-)

class InterfaceImplementer
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

Any thoughts?

Andrey
  • 59,039
  • 12
  • 119
  • 163
SmartestVEGA
  • 8,415
  • 26
  • 86
  • 139

7 Answers7

5

You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer

EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.

There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx

If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link

Darren
  • 136
  • 4
2

instead of creating a interface , why can we use the function directly like below

Are you asking what the point of the interface is?

Creating an interface allows you to decouple your program from a specific class, and instead code against an abstraction.

When your class is coded against an interface, classes that use your class can inject whichever class they want that implements this interface. This facilitates unit testing since not-easily-testable modules can be substituted with mocks and stubs.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
1

The purpose of the interface is for some other class to be able to use the type without knowing the specific implementation, so long as that type conforms to a set of methods and properties defined in the interface contract.

public class SomeOtherClass
{
     public void DoSomething(IMyInterface something)
     {
          something.MethodToImplement();
     }
}

public class Program
{
     public static void Main(string[] args)
     {
          if(args != null)
              new SomeOtherClass().DoSomething(new ImplementationOne());
          else
              new SomeOtherClass().DoSomething(new ImplementationTwo());
     }
}

Your example doesn't really follow that pattern, however; if one that one class implements the interface, then there really isn't much of a point. You can call it either way; it just depends on what kind of object hierarchy you have and what you intend to do for us to say whether using an interface is a good choice or not.

To sum: Both snippets you provide are valid code options. We'd need context to determine which is a 'better' solution.

Tejs
  • 40,736
  • 10
  • 68
  • 86
1

Interfaces are not required, there is nothing wrong with the last section of code you posted. It is simply a class and you call one of it's public methods. It has no knowledge that an interface exists that this class happens to satisfy.

However, there are advantages:

  • Multiple Inheritance - A class can only extend one parent class, but can implement any number of interfaces.
  • Freedom of class use - If your code is written so that it only cares that it has an instance of SomethingI, you are not tied to a specific Something class. If tomorrow you decide that your method should return a class that works differently, it can return SomethingA and any calling code will not need to be changed.
unholysampler
  • 17,141
  • 7
  • 47
  • 64
1

The purpose of interfaces isn't found in instantiating objects, but in referencing them. Consider if your example is changed to this:

static void Main()
{
    IMyInterface iImp = new InterfaceImplementer();
    iImp.MethodToImplement();
}

Now the iTmp object is of the type IMyInterface. Its specific implementation is InterfaceImplementer, but there may be times where the implementation is unimportant (or unwanted). Consider something like this:

interface IVehicle
{
    void MoveForward();
}
class Car : IVehicle
{
    public void MoveForward()
    {
        ApplyGasPedal();
    }
    private void ApplyGasPedal()
    {
        // some stuff
    }
}
class Bike : IVehicle
{
    public void MoveForward()
    {
        CrankPedals();
    }
    private void CrankPedals()
    {
        // some stuff
    }
}

Now say you have a method like this somewhere:

void DoSomething(IVehicle)
{
    IVehicle.MoveForward();
}

The purpose of the interface becomes more clear here. You can pass any implementation of IVehicle to that method. The implementation doesn't matter, only that it can be referenced by the interface. Otherwise, you'd need a DoSomething() method for each possible implementation, which can get messy fast.

David
  • 208,112
  • 36
  • 198
  • 279
0

Interfaces make it possible for an object to work with a variety of objects that have no common base type but have certain common abilities. If a number of classes implement IDoSomething, a method can accept a parameter of type IDoSomething, and an object of any of those classes can be passed to it. The method can then use all of the methods and properties applicable to an IDoSomething without having to worry about the actual underlying type of the object.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

The point of the interface is to define a contract that your implementing class abides by.

This allows you to program to a specification rather than an implementation.

Imagine we have the following:

public class Dog
{
    public string Speak()
    {
        return "woof!";
    }
}

And want to see what he says:

public string MakeSomeNoise(Dog dog)
{
    return dog.Speak();
}

We really don't benefit from the Interface, however if we also wanted to be able to see what kind of noise a Cat makes, we would need another MakeSomeNoise() overload that could accept a Cat, however with an interface we can have the following:

public interface IAnimal
{
    public string Speak();
}

public class Dog : IAnimal
{
    public string Speak()
    {
        return "woof!";
    }
}

public class Cat : IAnimal
{
    public string Speak()
    {
        return "meow!";
    }
}

And run them both through:

public string MakeSomeNoise(IAnimal animal)
{
    return animal.Speak();
}
mynameiscoffey
  • 15,244
  • 5
  • 33
  • 45