Tuesday, February 16, 2010

C# Interface Implementation

Interface implementation can be confusing…

I see a feature in C# that can be very confusing. In theexample below we have a class (Test) that implements 2 interfaces(I1 and I2). So the logic says that we should have implementations in the classTest for both MyFunction() methods from I1 and I2. BUT!As you see in the example below everything works fine with only 1 implementation.This is not as correct as we expect, because we can't be sure which of the two interfacesis implemented in the MyFunction method in class Test.So the solution is in another example (EXAMPLE2).In Example2 MyFunction() is implemented in class Test for each interface, by using a different method. (I1.MyFunction() -> for I1, I2.MyFunction() -> for I2).So now everything is clear, isn't it?

//EXAMPLE 1
using System;

namespace PavelTsekov
{
interface I1
{
void MyFunction();
}
interface I2
{
void MyFunction();
}
class Test : I1,I2
{
public void MyFunction()
{
Console.WriteLine("Guess which interface I represent???!");
}
}
class AppClass
{
public static void Main(string[] args)
{
Test t=new Test();
I1 i1=(I1)t;
i1.MyFunction();
I2 i2=(I2)t;
i2.MyFunction();
}
}
}

//EXAMPLE 2
using System;

namespace PavelTsekov
{
interface I1
{
void MyFunction();
}
interface I2
{
void MyFunction();
}
class Test : I1,I2
{
void I1.MyFunction()
{
Console.WriteLine("Now I can say this here is I1 implemented!");
}
void I2.MyFunction()
{
Console.WriteLine("Now I can say this here is I2 implemented!");
}
}
class AppClass
{
public static void Main(string[] args)
{
Test t=new Test();
I1 i1=(I1)t;
i1.MyFunction();
I2 i2=(I2)t;
i2.MyFunction();
}
}
}

Related Articles :

No comments:

Post a Comment