3
Reply

.NET Interview questions for Interfaces:- If A class inherits from multiple interfaces and the interfaces have same method names. How can we provide different implementation?.

    Explicit Interface Implementation

    Implementing multiple interfaces can sometimes result in a collision between member signatures. You can resolve such collisions by explicitly implementing an interface member. Consider the following example:

     

    interface I1 { void Foo(); }

    interface I2 { int Foo(); }

     

    public class Widget : I1, I2

    {

        public void Foo()

        {

            Console.WriteLine("Widget's implementation of I1.Foo");

        }

        int I2.Foo()

        {

            Console.WriteLine("Widget's implementation of I2.Foo");

            return 42;

        }

    }

    We can provide the implementation from this way given below


    Program :


    using System;
    interface IApple
    {
    void fruitName();
    }
    interface IMango
    {
    void fruitName();
    }
    class Fruits : IApple, IMango
    {
    void IMango.fruitName()
             {
                 Console.WriteLine("This is a Mango class.");
             }
             void IApple.fruitName()
             {
                 Console.WriteLine("This is an Apple class.");
             }
             public static void Main()
    {
    Fruits f = new Fruits();
                 ((IApple)f).fruitName();
                 ((IMango)f).fruitName();
                 Console.ReadLine();
    }
    }


    Answer:

    This is again one those typical .NET Interview questions which move around interfaces to confuse the developer.

    For providing different implementation you can qualify the method names with interface names as as shown below. A reference to I1 will display "This is I1" and reference to I2 will display "This is I2". Below is the code snippet for the same.

    interface I1  
    {
    void MyMethod();

    interface I2 

    void MyMethod(); 

    class Sample : I1, I2 

    public void I1.MyMethod() 

    Console.WriteLine("This is I1"); 
    }
    public void I2.MyMethod() 

    Console.WriteLine("This is I2"); 
    }  
    }

    50 .NET Interview questions and answers