The question : Are you able to call explicitly implemented method of an interface using object of concrete class?
This was one of the topic for discussion in our office, last week.Look at the below code.
public interface I1
{
public void Foo();
}
public class C1 : I1
{
#region I1 Members
void I1.Foo()
{
Console.WriteLine("In Foo method");
}
#endregion
}
If we have a structure like above can we call the method Foo as follows?
C1 c = new C1(); c.Foo();
In the initial look we may think what is wrong in it? But this is not possible.Most of us were really new to this particular scenario because we are all working in VB.Net for last one year.There were so many comments such as bug in .net,.net is not good etc…But after a while we got the solution from another question.What was that question?
In the above example add one more interface say I2 with same method Foo() and implement the same in class C1.Now if we try to call method Foo() by using variable of class C1 obviously there will be an ambiguity and the solution to avoid that state is the limitation of this call.
Everybody became happy like ending of an old Indian movie.
In VB.Net this is avoided by using the implements keyword.ie function Foo1() in class can implement an interface function Foo() and hence the concrete class variable can call the interface method as Foo1().See the code snippet below.
Public Interface I1
Sub Foo()
End Interface
Public Interface I2
Sub Foo()
End Interface
Public Class C1
Implements I1, I2
Public Sub Foo() Implements I1.Foo
End Sub
Public Sub Foo1() Implements I2.Foo
End Sub
End Class
Happy coding...
No comments:
Post a Comment