1

I am wondering if someone can advice if a class can implement the following interface at one time?

interface a1
{
   int mycount;
}

interface a2
{
   string mycount;
}

interface a3
{
   double mycount;
}
Alag20
  • 161
  • 1
  • 8

1 Answers1

6

None of your interfaces will compile, I'll assume they are methods and not fields.

The only way to implement multiple interfaces with conflicting membernames is by using explicit implementation:

interface a1
{
   int mycount();
}

interface a2
{
   string mycount();
}


class Foo : a1, a2
{
    int a1.mycount()     { ... }
    string a2.mycount()  { ... }


    // you can _only_ access them through an interface reference
    // even Bar members need to typecast 'this' to call these methods
    void Bar()
    {
         var x = mycount();               // Error, won't compile
         var y = (this as a2).mycount();  // Ok, y is a string
    }
}
H H
  • 263,252
  • 30
  • 330
  • 514
  • Thanks Henk. this is assuming that you have changed the datamembers into methods and I am aware that this implementation will work. My problem is that at a recent interview I had the same question and I was declined on my answer - that datamembers of same name from different interface is not possible to inherit into same class. So I want to confirm that this is correct. For some reason the interviewer thought otherwise which got me completely confused. – Alag20 May 11 '13 at 09:53