More interesting stuff on Interfaces..
Try these:
1. Create an Interface with a method
2. Create a class that implements this interface
3. Create a class that derives from the class above and also implements the interface.
Does your compiler allow this?
VB.NET does not allow you to do this. C#however, is comfortable with this. This because C# allows separate implementations for Interface methods. Something like:
public class Derived: Base, IMyItf
{
public int Func(int i,int j)
{
return 100;
}
int IMyItf.Func(int i,int j)
{
return 1000;
}
}
There is no such facility in VB.NET :(
Secondly, try this:
1. Create an interface with a method
2. Create a class and implement the interface
3. Create a class derived from the class above, have a method with the same signature as the one in base class
Now, which method is called if I use an Interface reference to call upon the method ? Can you explain??
Interestingly, the one in the base class is called irrespectively of whether you qualify your derived class method with Shadows or not. This is because, VB.NET requires you to explicitly mention that you are implementing the interface method(which is not mandatory in C#), Something like:
Public Function Add(ByVal a As Short, ByVal b As Short) As Object Implements IMyItf.Add
Return 100
End Function
In our example, only the base class has such an implementation. So, the method of the base is the one called. With C# too, the behavior is the same.
A Final twist, make the method in the base class private and repeat the steps. See what happens!
VB.NET will be glad to call upon the base class method though it is private. Remember, access specifiers are of no consequence here for calling methods through interface references.
With C# it is a slightly different story. C# will throw a compiler error complaining that the method (in the base) needs to public. However, if you have a separate interface method (like the example in Q1), that method will be called. Note that the method will not need an access specifier. In fact C# doesn’t allow you to add one either!