Thursday, April 26, 2012

casting a child class to a parent interface

There is an example like this in "C# 4.0 in a Nutshell" that I like:

namespace Whatever
{
   public interface Ape
   {
      int UseTool();
   }
}

 
 

Let's say Man inherits from Ape like so:

namespace Whatever
{
   public class Man : Ape
   {
      public string Speak()
      {
         return "It is EASY for me to talk.";
      }
      
      public int UseTool()
      {
         return 42;
      }
   }
}

 
 

Then this test would work as Ape has placeholder for UseTool() to be filled by Man.

[TestMethod]
public void ApeMayUseTool()
{
   Man man = new Man();
   Ape ape = man;
   Assert.AreEqual(ape.UseTool(), 42);
}

 
 

One could also not make our ape Speak() however. The following line will not compile.

ape.Speak();

 
 

Also, if one uses a class instead of an interface, the UseTool method CANNOT be private like so:

namespace Whatever
{
   public class Ape
   {
      private int UseTool()
      {
         return 21;
      }
   }
}

 
 

I made the mistake of thinking the above was feasible.

No comments:

Post a Comment