Search code examples
c#inheritancebuilder

Builder Pattern using Inheritance


I have CommonRequestBuilder and SpecificRequestBuilder, that look like this.

public class CommonRequestBuilder 
{
    protected readonly BigRequest _request;

    public CommonRequestBuilder()
    {
         _request = new BigRequest();
    }

    public CommonRequestBuilder WithExtras()
    {
        // add extra stuff to _request
        return this;
    }

    public BigRequest Build()
    {
        return _request;
    }
}

public class SpecificRequestBuilder : CommonRequestBuilder
{
    public SpecificRequestBuilder WithDetails()
    {
        // add some stuff to _request
        return this;
    }

    public BigRequest Build()
    {
        return _request;
    }
}

The issue with this pattern, is that if I use SpecificRequestBuilder like this:

_specificRequestBuilder.WithExtras().WithDetails(); // WithDetails() is not found

In above code WithDetails() cannot be resolved because I am getting the base class from WithExtras(). I can re-arrange the methods to make it work, but is there a way I can update the classes so that any order works?


Solution

  • You'll have to use the new keyword in your SpecificRequestBuilder to have a method with a different return type:

    public class SpecificRequestBuilder : CommonRequestBuilder
    {
        public SpecificRequestBuilder WithDetails()
        {
            // add some stuff to _request
            return this;
        }
    
    
        public new SpecificRequestBuilder WithExtras()
        {
            return (SpecificRequestBuilder)base.WithExtras();
        }
    }
    

    Online demo: https://dotnetfiddle.net/tU4hEM