Say, I have three interfaces:
public interface I1
{
void XYZ();
}
public interface I2
{
void XYZ();
}
public interface I3
{
void XYZ();
}
A class inheriting from these three interfaces:
class ABC: I1,I2, I3
{
// method definitions
}
Questions:
It compiles well and runs well too!
Does it mean this single method implementation is sufficient for inheriting all the three Interfaces?
I know it can done using explicit implementation but I'm not able to call them. :(
If you use explicit implementation, then you have to cast the object to the interface whose method you want to call:
class ABC: I1,I2, I3
{
void I1.XYZ() { /* .... */ }
void I2.XYZ() { /* .... */ }
void I3.XYZ() { /* .... */ }
}
ABC abc = new ABC();
((I1) abc).XYZ(); // calls the I1 version
((I2) abc).XYZ(); // calls the I2 version
You can call it. You just have to use a reference with the interface type:
I1 abc = new ABC();
abc.XYZ();
If you have:
ABC abc = new ABC();
you can do:
I1 abcI1 = abc;
abcI1.XYZ();
or:
((I1)abc).XYZ();
During implementation in a class do not specify modifier o/w you will get compilation error, also specify the interface name to avoid ambiguity.You can try the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleCSharp
{
class Program
{
static void Main(string[] args)
{
MyClass mclass = new MyClass();
IA IAClass = (IA) mclass;
IB IBClass = (IB)mclass;
string test1 = IAClass.Foo();
string test33 = IBClass.Foo();
int inttest = IAClass.Foo2();
string test2 = IBClass.Foo2();
Console.ReadKey();
}
}
public class MyClass : IA, IB
{
static MyClass()
{
Console.WriteLine("Public class having static constructor instantiated.");
}
string IA.Foo()
{
Console.WriteLine("IA interface Foo method implemented.");
return "";
}
string IB.Foo()
{
Console.WriteLine("IB interface Foo method having different implementation. ");
return "";
}
int IA.Foo2()
{
Console.WriteLine("IA-Foo2 which retruns an integer.");
return 0;
}
string IB.Foo2()
{
Console.WriteLine("IA-Foo2 which retruns an string.");
return "";
}
}
public interface IA
{
string Foo(); //same return type
int Foo2(); //different return tupe
}
public interface IB
{
string Foo();
string Foo2();
}
}