Take the 2-minute tour ×

I have the following situation

public interface IFoo
    void Bar();
public class Parent : IFoo
    public virtual void Bar(){}
public class Child : Parent, IFoo

    public override void Bar(){}


IFoo test = new Child();

test.Bar() always calls parent method!

Any help would be greatly appreciated!!

share|improve this question
The code you posted doesn't compile: there can't be the public modifier in IFoo.Bar. Hence we can't tell what's wrong with your code. Please post the real piece of code stripped down to the core of your problem. Most probably you implement IFoo.Bar explicitly in Parent and hence the Child won't override it. –  Ondrej Tucny Dec 6 '10 at 21:01
You are going to have to provide more code. This test causes Child.Bar to run over here. (And your interface definition is syntactically incorrect -- interface members don't have visibility specifiers.) –  cdhowie Dec 6 '10 at 21:01
Your example does not compile. Did you mean to make Parent an abstract class? –  asawyer Dec 6 '10 at 21:02
possible duplicate of problem with overriding virtual c# method (CORRECTED) –  Jacko Dec 6 '10 at 21:19
add comment

3 Answers

That should only happen if you implement it explicitly.

I just tested and it works.

share|improve this answer
add comment

WorksForMe: The problem must be somewhere else, when I run this code I see the child method is called, correctly. To compile your code I had to remove "public" from the method in the interface and I gave both Bar() methods a body.

share|improve this answer
add comment

C# 4.0 says that you have an error in syntax - public interface IFoo { void Bar(); } - access modifiers are not valid here So, if remove "public", code will run with child version of method as planned by you

share|improve this answer
If it doesn't compile, it's not going to run at all. Therefore this cannot be the real problem. I suspect the OP has posted fabricated code that is similar to the real code but not close enough for us to diagnose the actual problem. (And this fabricated code has syntax errors; presumably the real code does not.) –  cdhowie Dec 6 '10 at 21:05
yes, but in this situation - this is one right solution - syntax error in interface declaration, becouse in all other cases "override" will overrride base method –  Ivan Manzhos Dec 6 '10 at 21:11
add comment

Your Answer


