44

I've been developing software in C# for a while, but one major area that I don't use effectively enough is interfaces. In fact, I'm often confused on the various ways they can be used and when to use them. For example, I know methods can return interfaces, can take them as parameters, can be derived from them etc. This concept is a definite weakness for me

I was wondering if anyone knew of a source / tutorial that clearly and thoroughly explains interfaces in depth and the various ways they can be used?

Hosea146
  • 7,412
  • 21
  • 60
  • 81
  • 2
    I had this question crossed my mind with slightly different flavor a few months back and i asked it on Programmers. You might also like to read it . **[Why are interfaces useful](http://programmers.stackexchange.com/questions/108240/why-are-interfaces-useful)** Trust me, Once you visit this link, you won't go anywhere else. – Pankaj Upadhyay Jan 02 '12 at 13:25

2 Answers2

58

Description

Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from different classes through the same Interface reference, whereas using virtual functions we can invoke functions from different classes in the same inheritance hierarchy through the same reference.

For example:

public class FileLog : ILog
{
    public void Log(string text)
    {
        // write text to a file
    }
}

public class DatabaseLog : ILog
{
    public void Log(string text)
    {
        // write text to the database
    }
}

public interface ILog
{
    void Log(string text);
}

public class SomeOtherClass
{
    private ILog _logger;

    public SomeOtherClass(ILog logger)
    {
        // I don't know if logger is the FileLog or DatabaseLog
        // but I don't need to know either as long as its implementing ILog
        this._logger = logger;
        logger.Log("Hello World!");
    }    
}

You asked for tutorials.

Tutorials

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • reading this, i'm assuming from your `SomeOtherClass` example you wouldn't use D.I for the ILog object, you'd inject it at time of instantiating, so can dictate the type of ILogger you wish to use, i.e `var someClass = new SomeOtherClass(new FileLogger()); ` – Gweaths Nov 16 '21 at 10:53
5

Interfaces are generally used to force implementing classes to obey a certain contract (meaning to have certain methods). Sometimes they are just used as markers i.e. they have no methods declared but enable some code generator to generate special code for the implementing class.

Having said this, interfaces are not really a "tool" in their own right, so they don't serve a particular functional purpose, but they can greatly simplify the design of your application and are used extensively in OO design patterns. A basic resource is this tutorial: http://www.csharp-station.com/Tutorial/CSharp/Lesson13

Tudor
  • 61,523
  • 12
  • 102
  • 142