Jacko
Jacko

Reputation: 13195

Unable to override virtual c# method

I have the following code

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(); 

test.Bar() always calls parent method

Any help would be greatly appreciated

Upvotes: 0

Views: 1698

Answers (4)

Ivan Manzhos
Ivan Manzhos

Reputation: 743

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

Upvotes: 0

GTRekter
GTRekter

Reputation: 1007

The code is correct.

public interface IFoo
{
    string Bar();
}
public class Parent : IFoo
{
    public virtual string Bar() 
    {
        return "Hello world";
    }
}
public class Child : Parent, IFoo
{

    public override string Bar() 
    {
        return "Hello world after override";
    }
}
static void Main(string[] args)
{
    IFoo test = new Child();
    Console.WriteLine(test.Bar());

    Console.ReadLine();
}

The output is:

Hello world after override

Upvotes: 1

redtuna
redtuna

Reputation: 4600

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.

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

That should only happen if you implement it explicitly.

I just tested and it works.

Upvotes: 1

Related Questions