1

I have an abstract base class and I'm inheriting from it in an extension assembly. And here is my code region Contract Assembly

public interface IDummy
{
    int ForAbstractMethod();
    int ForVirtualMethod();
}

public abstract class BaseClass : IDummy
{
    public abstract int ForAbstractMethod();

    public virtual int ForVirtualMethod()
    {
        //Some base functionality
        return 0;
    }
}
#endregion

#region Extension Assembly

public class SomeExtension : BaseClass
{
    public override int ForAbstractMethod()
    {
        //I implement this method here, which is defined abstract in base class and this one works fine.
        return 100;
    }

    public override int ForVirtualMethod()
    {
        //Even though I override the virtual one here, still the one in the base class executes.
        return 1;
    }
}

#endregion


#region Main Program Assembly which references Contract Assembly

public class Program
{
    void Main()
    {
        //... compose catalog and other stuff

        IDummy dummy = someFactory.GetInstanceFromCatalog<IDummy>();//I get an instance
        int a = dummy.ForAbstractMethod();//this works as expected and returns 100
        a = dummy.ForVirtualMethod();//here I expect it to return 1 since I overrode it in child class, but it returns still 0.

        //...other stuff
    }
}

Are there any differences between overriding virtual and abstact methods that I am not aware of or this is a specific case for MEF? Thanks for any help...

ayk
  • 1,407
  • 2
  • 19
  • 26

1 Answers1

3

You're not declaring ForVirtualMethod as virtual on BaseClass. Change it to this

public virtual int ForVirtualMethod()
{
    //Some base functionality
    return 0;
}

Check MSDN for more details about virtual members declaration

The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • I'm so sorry. I forgot to add virtual keyword. It is actually virtual in my real code. I just tried to clarify things by writing some dummy code and forgot to add virtual. – ayk Jun 12 '13 at 13:47
  • @dopache: that's weird. What does `GetInstanceFromCatalog` do? – Claudio Redi Jun 12 '13 at 14:22
  • That's just a piece of code for readers to mention that dummy instance didn't came out of nowhere. – ayk Jun 12 '13 at 15:30