Thursday, May 3, 2012

A class and an interface that really need each other!

Here is some more magic from "C# 4.0 in a Nutshell."

namespace Whatever
{
   public interface IFoo
   {
      string SaySomething();
   }
}

 
 

There is no way to call the SaySomething method without casting an instance of Foo to an instance of IFoo.

namespace Whatever
{
   public class Foo : IFoo
   {
      string IFoo.SaySomething()
      {
         return "I can talk!";
      }
   }
}

 
 

This test passes.

[TestMethod]
public void TestMethod()
{
   Foo foo = new Foo();
   IFoo ifoo = (IFoo) foo;
   Assert.AreEqual(ifoo.SaySomething(), "I can talk!");
}

No comments:

Post a Comment