1

I created this interface:

public interface IPhrase
{
    int CategoryId { get; set; }
    string PhraseId { get; set; }
    string English { get; set; }
    string Romaji { get; set; }
    string Kana { get; set; }
    string Kanji { get; set; }
}

and this class:

public class Phrase : IPhrase
{
    public Phrase()
    {
    }

    public int CategoryId { get; set; }
    public string PhraseId { get; set; }
    public string English { get; set; }
    public string Romaji { get; set; }
    public string Kana { get; set; }
    public string Kanji { get; set; }
}

Here this code returns data and typecasts it to Phrase:

var phrases = db2.Query<Phrase>("SELECT * FROM Phrase", ans);
var phrases = db2.Query<IPhrase>("SELECT * FROM Phrase", ans);

What I would like to know is if there is any difference / advantage in my using the IPhrase here or Phrase? Also what advantages are there (if any) in my creating a IPhrase interface in this example. Does that lead to more readable code?

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 4
    If you at some point decide to use different implementation of `IPhrase` using interface here will save you maintenance time, this is one of the reasons why interfaces exist in the first place. Using concrete class gives you no benefits in this case – slawekwin Oct 21 '16 at 11:53
  • The advantage is that the former will actually compile and run, while the latter will either refuse to compile (`where T : class`) or throw an exception at runtime that it can't instantiate an interface. Please elaborate on your question and share your research. Is it _"Why would one use interfaces?"_, then try searching as that has been asked plenty of times before. If it's anything else, [edit] your question to make it answerable. – CodeCaster Oct 21 '16 at 11:59
  • I am not sure that EF/Linq (whatever) will work with an interface as it needs to create a concrete type to return from the query. In this case that would not be possible. Also there are almost never real benefits to intefaces when dealing with simple entities (types that have no real behavior of their own). – Igor Oct 21 '16 at 11:59
  • Can the answerers and upvoters please read [ask] and [C# interfaces - What's the point?](http://stackoverflow.com/questions/6802573/), [When to Use Interfaces](https://msdn.microsoft.com/en-us/library/3b5b8ezk(v=vs.90).aspx), [Why are interfaces useful?](http://softwareengineering.stackexchange.com/questions/108240/), [Why I should go for Interfaces in C# when I can implement the methods directly](http://stackoverflow.com/questions/10914802/) and so on? We don't need another handful of explanation in layman's terms when well-defined, older questions about the exact same subject already exist. – CodeCaster Oct 21 '16 at 12:22

5 Answers5

3

An interface is a contract that guarantees, any class implementing the interface will implement the methods and properties defined in the interface. This allows you to use the interface to create methods, lists, etc. which accept any class that implements the interface e.g.

public interface IExample
{
    int GetInt();
}

public void ProcessInt(IExample value)
{
    var tempInt = value.GetInt();
    // Do processing here
}

This allows any concrete class that implements interface IExample to be passed to this method. The method is assured that any concrete class passed will have the method GetInt implemented.

Kevin
  • 1,462
  • 9
  • 9
  • Yes, this is a very nice and simple explanation of why one would use interfaces, but I don't see its relation to the question. – CodeCaster Oct 21 '16 at 12:00
  • @CodeCaster The hope is that a better understanding of interfaces and how they are used will allow the OP to understand the advantage of using interfaces in the appropriate circumstances which, to me, does seem to be at the heart of his question. – Kevin Oct 21 '16 at 12:05
  • Yeah but it's a terrible question, and the 621th by this OP at that, so you shouldn't really answer unclear questions is what I meant. :) – CodeCaster Oct 21 '16 at 12:07
  • @CodeCaster - fair enough – Kevin Oct 21 '16 at 12:07
2

With objects you can inherit from to things:

  1. Other Objects
  2. Interfaces

Object

If you have an Animal object, a Dog object can inherit from it as it is an animal.

With Object inheritance think of the phrase: I am a ...._yourObject_...

Interface

With an interface you can think of it as a describer for that object. Such as IWalkOnTwoLegs or ICanSwim.

So think of the phrase : I can do ...._yourInterface_..

Now to answer your question, would it make a difference if you use an interface or not?

Well, it wouldn't in this case but if you extend your phrases and create a Question object and a Statement object, for example, and they inherit from Phrase, you have a choice where you can return all phrases (questions and statements) or only phrases that are Questions or only Statements.

You can also apply an interface saying IAmInFrench and IAmInSpanish to your phrase so you can have extended SpanishPhrase and FrenchPhrase objects. Now you can return either all phrases whether they are questions, statements, in a different language, or you can be specific and return only french phases.

Where I find interfaces are most useful are for registration of different types in unity.

Where it will make a difference:

Where it will definitely make a difference is if there is a property on the object that isn't on the interface, then if you return the interface you will not be able to access that property very easily unless you type cast.

eg:

public class Phrase : IPhrase
{
    public Phrase()
    {
    }

    public int CategoryId { get; set; }
    public string PhraseId { get; set; }
    public string English { get; set; }
}

And interface

public interface IPhrase
    {
      int CategoryId { get; set; }
    }

You will not be able to access the property English if you return the interface:

var phrases = db2.Query<IPhrase>("SELECT * FROM Phrase", ans);
var eng = phrases[0].English; //**THIS WONT WORK**
1

There is no difference between using an interface and a concrete object locally, as in your example. The main difference is when you are sending interfaces vs concrete classes as parameters in APIs or constructors parameters, where is preferably using interfaces so you can achieve decouple and testability.

Still for your question the short answer is no, there is no difference, whether you want to use interfaces or concrete objects as local variables is your own choice (what seems more readable to you). Do not forget that fields and properties are good to be declared as interfaces which provides more flexibility.

One last thing which should be considered when using a concrete object instead of an interface even locally is that you may want someday to change the signature of the method which provides you that object to return another kind of object which implements the same interface, and in that case you should change the local variable too (even if it's not so bad and it happens very rarely I had to note it), as in the following example:

interface IAnimal
{
    void Run();
}

class Cat : IAnimal
{
    public void Run()
    {
        //...
    }
}

class Dog : IAnimal
{
    public void Run()
    {
        //...
    }
}

If in your code you have a method which returns a Cat that you use:

Cat GetAnimal()
{
    return new Cat();
}

Cat myAnimal = GetAnimal(); //note that here it is expected a Cat
myAnimal.Run();  

Then if you change the GetAnimal signature to return a Dog, your code should be changed in order to compile to:

Dog myAnimal = GetAnimal(); //note that here it is expected a Cat
myAnimal.Run();  

But if you are using an interface there are less chances that your code will need to be changed when method's signatures ar changed:

IAnimal myAnimal = GetAnimal(); //this is working whether a Cat or a Dog is received.
myAnimal.Run(); 

But again this is happening relatively rarely. Sorry for the silly Cat & Dog example!

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
0

A class is a template for an object. It is essentially a blueprint. So for a light there a button that is on and off. Say when you call this method a value is sent to some controller that turns it on and off. All you have to do is call the method for on/off and viola it works.

An interface is very similar. Here the on/off method might not be implemented. You actually have to go and write the code to turn the light on and off but you must write the on/off method or it cannot be that interface. Say there is a new type of light that has dimming functionality. An interface allows you to implement this new feature for a different type of light. So its basically telling you that you have to have this stuff done (on/off) for it to be a light but we don't care how you implement it. Some parts of the interface may be implemented for you, but other parts you have to implement.

When would an interface make sense? A situation where you have many objects that are very similar in nature but differ slightly in implementation. For example say you have many types of shapes. Each is going to have an area. The calculation is different for a triangle than it is for a circle. Now say you have hundreds of shapes that need to be constructed, you wouldn't keep making new objects for each type of shape, you would just implement the interface. This gives somebody the power to create shapes, maybe even custom shapes, with similar methods but different implementations.

MikeB0317
  • 1
  • 1
0

Your answer depends on the way you want to use your future classes. Interfaces are contracts to ensure descendant classes have all definitions of interface. So This is useful when you want to use polymorphism. in this way, you can define all common specifications of an object in an interface class. Another advantage of interfaces is that your class can inherit from multiple interfaces, which is not allowed for other type of classes in C#. Here is an example code. Hope to be useful for you:

public interface IShape
{
    float Area { get; }
    float circumference { get; }
}
public class Rectangle : IShape
{
    private float l, h;
    public Rectangle( float length, float height ) { l = length; h = height; }
    public float Area { get { return l * h; } }
    public float circumference { get { return ( l + h ) * 2; } }
}
public class Circle : IShape
{
    private float r;
    public Circle( float radius ) { r = radius; }
    public float Area { get { return (float)Math.PI * r * r; } }
    public float circumference { get { return (float)Math.PI * r * 2; } }
}

public class SomeClass
{
    IShape[] shapes = new IShape[] // Can store all shapes regardless of its type
    {
        new Rectangle( 10f, 20f ),
        new Rectangle( 15f, 20f ),
        new Rectangle( 11.6f, .8f ),

        new Circle( 11f ),
        new Circle( 4.7f )
    };
    public void PrintAreas()
    {
        foreach ( var sh in shapes )
            Console.WriteLine( sh.Area ); // prints area of shape regardless of its type
    }

    public void PrintCircumference(IShape shape )
    {
        Console.WriteLine( shape.circumference ); // again its not important what is your shape, you cant use this function to print its cicumference
    }
}
Amin
  • 221
  • 3
  • 13