Translate

Tuesday, October 8, 2013

C# When to explicity implement an interface

You will explicitly implement interface mainly for these reasons

1>If two of the implemented interfaces have the same method signature.Then implementing them explicitly is the only way.

using System;

namespace ConsoleApplication5
{
    class Program
    {

        static void Main(string[] args)
        {
            var calc = new Calculator();

            /*Note: When you implement an interface explicitly,
            then casting your class instance into that interface,
             is the only way to access it's methods*/

            ((IOrderCount)calc).GetCount();    //Displays Order Count
            ((IInventoryCount)calc).GetCount();//Displays Inventory Count
        }
    }

    interface IOrderCount
    {
         void GetCount();
    }

    interface IInventoryCount
    {
        void GetCount();
    }

    public class Calculator  : IOrderCount, IInventoryCount
    {
          void IOrderCount.GetCount()
        {
            Console.WriteLine("Order Count");
        }

        void IInventoryCount.GetCount()
        {
            Console.WriteLine("Inventory Count");
        }
    }

}


2>Another reason you want to explicitly implement an interface is if you want to focus only on that interface when using it. For instance in the example above, when I do  ((IOrderCount)calc)  I can only access methods on IOrdercount.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator