Reputation: 3109
I've got the code below, I use class "B" to inherit class "A" while I wish to implement F function from interface IMy. But compiler tells my I'm hiding interface method "F". So the running result is "A".
I expect this program to output "B". I don't wish to use implicit interface implementation as I wish to use normal polymorphism in main function.
How to correct my code? Thanks.
public interface IMy
{
void F();
}
public class A : IMy
{
public void F()
{
Console.WriteLine("A");
}
}
public class B : A
{
public void F()
{
Console.WriteLine("B");
}
}
class Program
{
static void Main(string[] args)
{
IMy my = new B();
my.F();
}
}
Upvotes: 1
Views: 737
Reputation: 14904
To override a method in C#, the method in base class needs to be explicitly marked as virtual
. It doesn't matter if the method implements an interface method or not.
public class A : IMy
{
public virtual void F()
{
Console.WriteLine("A");
}
}
public class B : A
{
public override void F()
{
Console.WriteLine("B");
}
}
Upvotes: 7
Reputation: 27377
Your current code is equivalent to:
public class A : IMy
{
public void F()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void F() // <--- Note 'new' here
{
Console.WriteLine("B");
}
}
You're implicitly marking the method as new, which will generate a compiler warning unless you explicitly write it.
What you actually want is to override the method, so declare that:
public class A : IMy
{
public virtual void F() // <--- Mark as virtual to allow subclasses to override
{
Console.WriteLine("A");
}
}
public class B : A
{
public override void F() // <-- Override the method rather than hiding it
{
Console.WriteLine("B");
}
}
Upvotes: 4