views:

378

answers:

8

I m trying to understand Interfaces so that I can implement them in my programs but I m not able to imagine how should i use them. Also give me some eg of using them with multiple inheritance in C#

+1  A: 

Interfaces simply define a contract of the public elements (e.g. properties, methods, events) for your object, not behavior.

interface IDog
{
    void WagTail();    //notice no implementation
    ISound Speak();    //notice no implementation
}

class Spaniel : IDog
{
    public void WagTail()
    {
        Console.WriteLine("Shook my long, hairy tail");
    }

    public ISound Speak()
    {
        return new BarkSound("yip");
    }

}

class Terrier : IDog
{
    public void WagTail()
    {
        Console.WriteLine("Shook my short tail");
    }

    public ISound Speak()
    {
        return new BarkSound("woof");
    }
}

UPDATE

In "real examples" I use interfaces with: - Unit Testing - GENERICS (e.g. Repository, Gateway, Settings)

interface Repository<T>{
    T Find(Predicate<T>);
    List<T> ListAll();
}

interface Gateway<T>{
    T GetFrom(IQuery query);
    void AddToDatabase(IEntity entityItem);
}

interface Settings<T>{
    string Name { get; set; }
    T Value { get; set; }
    T Default { get; }
}
Brett Veenstra
Not exactly what I would call a "real example"...just my opinion, but these kinds of examples (dogs, cats, cars and other abstractions) tend to do nothing to help anyone understand OOP concepts.
Gus
Sorry it wasn't a good example for you. I was trying to focus on the comparison to Abstract Base Class. Please see the ideas after the UPDATE demark.
Brett Veenstra
+6  A: 

A good example for an interface is a repository pattern. Your interface will define methods like Get, GetAll, Update, Delete, etc. No implementation, just function signatures.

Then, you can write a 'concrete' implementation of that class to work with, say, MySQL. Your UI should only refer to the interface, though.

Later, if you decide to change to Microsoft SQL, you write another concrete implementation, but your UI code doesn't have to change (much).

Multiple inheritance doesn't exist in C#, in the sense that you can only inherit from one 'concrete' class; though you can inherit (or 'implement') as many interfaces as you want.

mgroves
+1  A: 

Sometimes being too abstract just gets in the way and referring to implementation details actually clarifies things. Therefore, I'll provide the close to the metal explanation of interfaces that made me finally grok them.

An interface is just a way of declaring that a class implements some virtual functions and how these virtual functions should be laid out in the class's vtable. When you declare an interface, you're essentially giving a high-level description of a virtual function table to the compiler. When you implement an interface, you're telling the compiler that you want to include the vtable referred to by that interface in your class.

The purpose of interfaces is that you can implicitly cast a class that implements interface I to an instance of interface I:

interface I {
    void doStuff();
}

class Foo : I {
    void doStuff() {}

    void useAnI(I i) {}
}

var foo = new Foo();
I i = foo;  // i is now a reference to the vtable pointer for I in foo.
foo.useAnI(i);  // Works.  You've passed useAnI a Foo, which can be used as an I.
dsimcha
I doubt that a C# beginner knows about vtables :-)
Jakob Christensen
You may be right, though I didn't even grok any of OO until I understood function pointers and vtables. This is my point about how referring to implementation details can actually clarify things. Before I understood function pointers and vtables, OO just seemed way too abstract and arbitrary.
dsimcha
+1  A: 

Here is one (in Java, but this is not important since they're similiar): In my project I've created simple interface:

public interface Identifiable<T> {
    public T getId();
}

Which is simple replacement to some sorts of annotations. The next step: I've made all entity classes implement this interface.

The third step is to write some syntax-sugar-like methods:

public <T> List<T> ids(List<? extends Identifiable<T> entities) { ... }

This was just an example.

The more complex example is something like validation rules: you have some validation engine (probably written by you) and a simple interface for rule:

public interface ValidationRule {
    public boolean isValid(...);
}

So, this engine requires the rules to be implemented by you. And of course there will be multiple inheritance since you'll certainly wish more then a single rule.

Dair T'arg
A: 

Take a look at something you are familiar with - ie a List collection in C#. Lists define the IList interface, and generic lists define the IList interface. IList exposes functions such as Add, Remove, and the List implements these functions. There are also BindingLists which implement IList in a slightly different way.

I would also recommend Head First Design Patterns. The code examples are in Java but are easily translated into C#, plus they will introduce you to the real power of interfaces and design patterns.

DanDan
+3  A: 

I am writing a video game. In this video game I apply different forces to objects in the game. Thrust forces, impact forces, gravitational forces. While they are calculated differently, they all have the same basic elements. I need to call an update function that will evaluate the force and add the force to the object it's attached to.

So, what I've done is create an IForce interface that has an update function for its signature. All of my forces implement this interface:

public interface IForce
{
    void Update(Particle particle, GameTime gameTime);
}

Here is a sample implementation.

public class Spring : IForce
{
    private Particle ThisParticle;
    private Particle ThatParticle;

    private float K;

    public Spring(Particle thisParticle, Particle thatParticle, float k)
    {
        ThisParticle = thisParticle;
        ThatParticle = thatParticle;
    }

    public void Update(Particle particle, GameTime gameTime)
    {            
        float X = Vector3.Length(ThisParticle - ThatParticle);

        ThisParticle.Forces.Add(K * X);
    }
}

The update function has a simplified spring force update to make it easier to understand.

This helps in a few ways.

I can completely change the way a force is calculated without effecting other parts of my code. I do this all the time. Along the same lines, it is rediculously easy for me to add new forces. As long as it implements the IForce interface I know it will mesh well with my existing code.

Another way it helps is with handling a large number of forces. I have a force registry that has a List of IForce. Since all forces implement that interface and have an Update function it's very easy to update all the forces in my game. When I create the force I add it to the list. Then, I loop through the list and call each elements update function without worrying about what type of force it is and all my forces update.

I use interfaces every day in a lot of different situations. They are fantastic!

Eric
This scenario is good to understand interfaces but I need some more clarrification with a little implementation in the scenario you have explained. I m not able to imagine how did u implemented these forces in classes. I think you need to give the signature of ur function in your Interface IForce that you already told about. But how you are using it in different classes. Are you writing the defination of those functions in all the classes implementing those force.
Shantanu Gupta
A: 

Multiple inheritance is about having a class be usable in multiple situations: [pseudo code]

interface Shape {
    // shape methods like draw, move, getboundingrect, whatever.
}

interface Serializable {
    // methods like read and write
}

class Circle : public Shape, public Serializable {
    // TODO: implement Shape methods
    // TODO: implement Serializable methods
}

// somewhere later
{
    Circle circle;
    // ...
    deserializer.deserialize(circle);
    // ...
    graphicsurface.draw(circle);
    // ...
    serializer.serialize(circle);
}

The idea is that your Circle class implements two different interfaces that are used in very different situations.

Fozi
that's not multiple inheritance, just implementation of multiple interfaces. C# doesn't support multiple inheritance, as well it shouldn't.
David Lively
That's not C#..
Fozi
+1  A: 

The simple answer, in my opinion, and being somewhat new to interfaces myself is that implementing an interface in a class essentially means: "This class MUST define the functions (and parameters) in the interface".

From that, follows that whenever a certain class implements the interface, you can be sure you are able to call those functions.

If multiple classes which are otherwise different implement the same interface, you can 'cast' them all to the interface and call all the interface functions on them, which might have different effects, since each class could have a different implementation of the functions.

For example, I've been creating a program which allows a user to generate 4 different kinds of maps. For that, I've created 4 different kind of generator classes. They all implement the 'IGenerator' interface though:

public interface IGenerator {
    public void generateNow(int period);
}

Which tells them to define at least a "public generateNow(int period)" function.

Whatever generator I originally had, after I cast it to a "IGenerator" I can call "generateNow(4)" on it. I won't have to be sure what type of generator I returned, which essentially means, no more "variable instanceof Class1", "variable instanceof Class2" etc. in a gigantic if statement anymore.

Aeolun
I didn't get you, What actually trying to make me clear. This eg seems to be going into correct direction for the Question that I asked but still little bit in doubt about how you r using it in different different classes as you said --- "I returned, which essentially means, no more "variable instanceof Class1", "variable instanceof Class2" etc." I am not able to picturize how you r using this Interface to benefit into your code as well as in multiple interface
Shantanu Gupta