-1

I'm wondering why in the following example does the base method always get called even though I'm overriding it when the Factory Pattern "Builder" returns a new instance of the object?

interface FactoryInter 
{
    void MakeDetails();

}

class Builder {

    public static Builder getObject(string obj)
    {
        if(obj == "Cont")
        {
            return new Cont();
        }else{
            return new Builder();
        }

    }

    public void MakeDetails()
    {
        Console.WriteLine("I will always get called..");
    }

}

class Cont : Builder, FactoryInter {

    public void MakeDetails()
    {
        Console.WriteLine("Hello..");
    }

}

public class Test
{
    public static void Main()
    {
        Builder b = new Builder();
        b = Builder.getObject("Cont");

        b.MakeDetails();
        // your code goes here
    }
}

Any help would be greatly appreciated

Phorce
  • 4,424
  • 13
  • 57
  • 107

1 Answers1

7

You do not override it. You are hiding it. Method Cont.MakeDetails() is hiding the base class's MakeDetails method. For more details please see the below example:

class Base
{
    public void Hidden()
    {
        Console.WriteLine("Base!");
    }

    public virtual void Overrideable()
    {
        Console.WriteLine("Overridable BASE.");
    }
}

class Derived : Base
{
    public void Hidden()
    {
        Console.WriteLine("Derived");
    }

    public override void Overrideable()
    {
        Console.WriteLine("Overrideable DERIVED");
    }
}

Now testing them yields these results:

var bas = new Base();
var der = new Derived();

bas.Hidden(); //This outputs Base!
der.Hidden(); //This outputs Derived
((Base)der).Hidden(); 
//The above outputs Base! because you are essentially referencing the hidden method!

//Both the below output Overrideable DERIVED 
der.Overrideable();
((Base)der).Overrideable();

To override it, mark the base method as virtual and the derived one as override.

Savvas Kleanthous
  • 2,695
  • 17
  • 18
  • SKleanthous has it spot on. A more detailed explanation can be found [here](http://msdn.microsoft.com/en-us/library/ms173153.aspx) – Gridly Jul 25 '14 at 14:39