I have a question regarding Interface. There are 2 interface both contain the same Method Test(). Now I'm inheriting both the interface in Sample class.I want to know which Interface's method will be called? My code sample is below:
interface IA
{
void Test();
}
interface IB
{
void Test();
}
class Sample: IA, IB
{
public void Test()
{
Console.WriteLine("Which interface will be implemented IA or IB???!");
}
}
class Program
{
public static void Main(string[] args)
{
Sample t = new Sample();
t.Test();//Which Interface's Method will called.
Console.ReadLine();
}
}
Thanks Vijendra Singh
The result will be the same for both. If you want different behaviour per interface, you have to explicitly implement them:
interface IA
{
void Test();
}
interface IB
{
void Test();
}
class Sample: IA, IB
{
void IA.Test()
{
Console.WriteLine("Hi from IA");
}
void IB.Test()
{
Console.WriteLine("Hi from IB");
}
public void Test() //default implementation
{
Console.WriteLine("Hi from Sample");
}
}
class Program
{
public static void Main(string[] args)
{
Sample t = new Sample();
t.Test(); // "Hi from Sample"
((IA)t).Test(); // "Hi from IA"
((IB)t).Test(); // "Hi from IB"
Console.ReadLine();
}
}
If you want default behaviour, create a method with the same signature (thus an implicit interface implementation) and add code for that case. Usually, you just want the explicit implementation though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With