mnn
mnn

Reputation: 2010

Overloading with argument types that are base and inherited class

I have something like this:

class BaseArg { }
class DerivedArg : BaseArg { }

interface IDoSomething
{
    void DoSomething();
}

class A : IDoSomething
{
    public BaseArg Value { get; set; }

    public A(BaseArg value)
    {
        this.Value = value;
    }

    public static A Create(BaseArg arg)
    {
        return new A(arg);
    }

    public static B Create(DerivedArg arg)
    {
        return new B(arg);
    }

    public virtual void DoSomething()
    {

    }
}

class B : A
{
    public DerivedArg DerivedValue { get; set; }

    public B(DerivedArg value)
        : base(value)
    {
        this.DerivedValue = value;
    }

    public override void DoSomething()
    {
        // does something different from A.DoSomething()
        // uses additional stuff in DerivedArg
    }
}

However, even when I do this:

DerivedArg arg = new DerivedArg();
A a = A.Create(arg);

A.Create(BaseArg arg) is called (and thus A is created, which was not the intention).

Am I missing something here? If so, how should I rewrite this without using weird stuff such as conditions on arg as DerivedArg.

Upvotes: 0

Views: 65

Answers (1)

Alex
Alex

Reputation: 35407

The correct factory method is getting executed. Set a breakpoint inside of:

    public static B Create(DerivedArg arg)
    {
        return new B(arg); /* set breakpoint */
    }

It appears to you that it isn't being executed since you've defined the local variable of type A:

A a = A.Create(arg);

public static B Create(DerivedArg arg) is being called properly and an instance of type B is being returned and boxed as type A.

Upvotes: 2

Related Questions