Declaring and Using an Object of Type Interface

One particular scenario with C# interfaces is very confusing for beginners. Suppose you see code like this:
 
ICar mySedan = new Sedan(2008);
 
What exactly is going on here? We have an object named mySedan, a constructor Sedan(), and an Interface ICar. You would expect the code to look like this:
 
Sedan mySedan = new Sedan(2008);
 
because an interface is a contract, or a template, which does not have any implementation. For example, consider these "normal" interface and class definitions:
 
// version #1 – "normal"
public class Sedan : ICar
{
  public int year;
  public Sedan(int y)
  {
    this.year = y;
  }
  public void display() // <- note this signature
  {
    Console.WriteLine("The year of the sedan is " + this.year);
  }
}
public interface ICar
{
  void display();
}
 
Here we have an interface ICar which says in essence, "When you define a class derived from me, you must code a display() method." The Sedan class derives from ICar as you’d expect and implements the display() method. Now to call this version you could use:
 
Sedan mySedan = new Sedan(2008);
mySedan.display();
// displays "The year of the sedan is 2008"
 
OK, so far so good. But because the Sedan class derives from ICar, you could also use this version:
 
ICar mySedan = new Sedan(2008);
mySedan.display();
// also displays "The year of the sedan is 2008"
 
which is the code I started this discussion with and explains one scenario where you can declare an object which has an Interface type. But now comes the tricky part. There is a scenario where you must declare an object which has an Interface type. Suppose you implement the Sedan class slightly differently:
 
// version #2: explicit Interface method definition
public class Sedan : ICar
{
  public int year;
  public Sedan(int y)
  {
    this.year = y;
  }
  void ICar.display() // <- note difference
  {
    Console.WriteLine("The year of the sedan is " + this.year);
  }
}
public interface ICar
{
  void display();
}
 
Here I use "an explicit interface implementation". Now to call this version, if you try the normal calling technique:
 
Sedan mySedan = new Sedan(2008);
mySedan.display();
// will not compile
 
your code will not compile. In this scenario you must declare the object as an Inteface type like this:
 
ICar mySedan = new Sedan(2008);
mySedan.display();
// displays "The year of the sedan is 2008"
 
To summarize, if you see an object declared as an interface type such as ISomething, then a.) it might be a case where you can change the type to a specific type, or b.) it might be a case of explicit interface implementation.
 
Advertisements
This entry was posted in Software Test Automation. Bookmark the permalink.