Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a particular explicitly declared interface method in C#

Tags:

c#

.net

interface

I have a doubt on how to call the method of particular interface (Say IA or IB or In...) in the following code. Please help me on how to call. I have commented the lines of code where I declare the interface methods "public" in which case it works. I dont know how to call it when I explicitly declare :( I am learning C#....

interface IA
    {
        void Display();
    }
    interface IB
    {
        void Display();
    }
    class Model : IA, IB
    {
        void IA.Display()
        {
            Console.WriteLine("I am from A");
        }
        void IB.Display()
        {
            Console.WriteLine("I am from B");
        }
        //public void Display()
        //{
        //    Console.WriteLine("I am from the class method");
        //}

        static void Main()
        {
            Model m = new Model();
            //m.Display();
            Console.ReadLine();
        }
    }
like image 281
Jasmine Avatar asked Feb 25 '13 20:02

Jasmine


2 Answers

To call an explicit interface method, you need to use a variable of the proper type, or directly cast to that interface:

    static void Main()
    {
        Model m = new Model();

        // Set to IA
        IA asIA = m;
        asIA.Display();

        // Or use cast inline
        ((IB)m).Display();

        Console.ReadLine();
    }
like image 130
Reed Copsey Avatar answered Oct 08 '22 16:10

Reed Copsey


The method that will be called depends on the type that calls it. For example:

Note, for sake of clarity, I create two items. In practice though, you don't want to do this, you should just cast the object between types.

static void Main(string[] args)
{
    // easy to understand version:
    IA a = new Model();
    IB b = new Model();

    a.Display();
    b.Display();

    // better practice version:
    Model model = new Model();

    (IA)model.Display();
    (IB)model.Display();
}

interface IA
{
    void Display();
}

interface IB
{
    void Display();
}

class Model : IA, IB
{
    void IA.Display()
    {
        Debug.WriteLine("I am from A");
    }

    void IB.Display()
    {
        Debug.WriteLine("I am from B");
    }            
}

Outputs:

I am from A
I am from B
like image 45
Adam K Dean Avatar answered Oct 08 '22 17:10

Adam K Dean