Home > Back-end >  Override function in interface
Override function in interface

Time:08-09

How to override functions with the same name and signature which are in two different interfaces, in a class that is inheriting both interfaces. 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 explicit 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;
}
  • Related