Home > other >  Over ride function in interface c#
Over ride function in interface c#

Time:08-06

How to over-ride a function with same name, same return type, same number of parameters and datatype in two different interface in same class inheriting both interface.###

How can I define two different logic for below two add() function declared in two interface inside same class. Is it possible ?
Note: This was an interview question I was asked.

Example:

interface example1
{
    int add(int a, int b);
}

interface example2
{
    int add(int a, int b);
}


public class cls : example1, example2
{
    public int add(int a, int b)
    {

        int c = a   b;
        return c;
    }
}

CodePudding user response:

There are several options when we have two or more interfaces with the same methods:

We can use explicit interface implementation:

public class cls : example1, example2 {
  // note abscence of "public", the method efficiently private
  int example1.add(int a, int b) => a   b;

   // note abscence of "public", the method efficiently private
  int example2.add(int a, int b) => Math.Abs(a)   Math.Abs(b);
}

The call wants cast to the required interface:

var demo = new cls();

Console.Write($"{((example1)demo).add(2, -3)} : {((example2)demo).add(2, -3)}");

If we have some method add as a default behaviour (say example1), we can use interface implementation for example2 only:

public class cls : example1, example2 {
  public int add(int a, int b) => a   b;

  int example2.add(int a, int b) => Math.Abs(a)   Math.Abs(b);
}

And now the call wants cast in case of example2 only:

var demo = new cls();

Console.Write($"{demo.add(2, -3)} : {((example2)demo).add(2, -3)}");

Finally, if both interfaces share the same method:

public class cls : example1, example2 {
  // Both interfaces example1 and example2 share the same method
  public int add(int a, int b) => a   b;
}

CodePudding user response:

A bit of semantics first, you do not inherit interfaces, you implement them.

That being said, the question is a bit unclear, but very likely they were asking about Explicit Interface Implementation.

public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}
  • Related