Better Grasp on Interfaces
<p>I have used a lot of abstract classes both for polymorphism, and obviously inheriting common function in subclasses.</p>

<p>I'm trying to use interfaces more. Yes, it's also use for polymorphism..for example using an IMyInterface param in a method that can take any subclass that implements IMyInterface.</p>

<p>Ok, now the thing I don't get though is why we should or always need to define our variables as IMyInterface instead of a type that has implemented that interface.</p>

<p>Example, take a look at this article:</p>

<p><a href="http://weblogs.asp.net/sfeldman/archive/2008/02/14/understanding-ioc-container.aspx" rel="nofollow">http://weblogs.asp.net/sfeldman/archive/2008/02/14/understanding-ioc-container.aspx</a></p>

<p>Ok, specifically this:</p>

<pre><code>  17:      private static void AppCode()
  18:      {
  19:        ConsoleLogger logger = new ConsoleLogger();
  20:        Gadget gadget = new Gadget(logger);
  21:        gadget.TurnOn();
  22:        gadget.TurnOff();
  23:      }
  24:    }
  25:  }

AppCode method (lines 19-22) is what we are interested in. A few question can be raised at this point:

   1. Why logger is of type ConsoleLogger and not ILogger? Isn't this wrong?
   2. Why gadget is of type Gadget and not IGadget? Same smell?
   3. What if we need to move logger implementer to a different layer than the ConsoleApp?
</code></pre>

<p>Here's the thing for me, I don't get why it's not a problem to just use the type Gadget and ConsoleLogger concrete methods.  Why in this top layer does it still need to be a var of type ILogger and IGadget?  I mean at this point I'm not seeing any need for polymorphism..but I"m missing the boat I guess here in my learning process.</p>

<p>Can someone explain why everyone wants to create interface params in your top layers for variables and assigning that variable to a type that has implemented that interface?  Why not just Gadget and ConsoleLogger, the very concrete class you want to use in the first place?  Yes Gadget and ConsoleLogger meet the contracts of the ILogger and IGadget...but I must be missing another reason here..fundamental reason.</p>

<p>If I make no sense, it's because I don't really know how to describe my question but I feel this is pretty clear.  Why use interface variables in a case like this?</p>

<p>It's almost like what I've seen out there is once you need to use a concrete type that has implemented an Interface that it looks to me that you should always set it to an interface variable, not a variable type of that subclass.  Is this right?</p>
