Question

I have been getting a lot of traction from a builder pattern as a public class member of another class:

public class Part
{
    public class Builder
    {
        public string Name { get; set; }
        public int Type { get; set; }

        public Part Build()
        {
            return new Part(Name, Type);
        }
    }

    protected Part(string name, int type)
    {
        ...
    }
}

Note protected constructor - I like how I HAVE to use the builder to get a Part. Calls to

Part p = new Part.Builder() { Name = "one", Type = 1 }.Build();

work great. What I would like to do is use this builder to serve up a special kind of part based on the Type (for example):

public class SpecialPart : Part
{
    protected SpecialPart(string name, int type) : base(name, type) { }
}

And a slight change to the builder:

public Part Build()
{
    if (Type == _some_number_)
        return new SpecialPart(Name, Type);
    return new Part(Name, Type);
}

But this doesn't work - Part.Builder can't see SpecialPart's protected constructor. How can I get Builder to work with descendents of Part and get the same must-have-a-builder semantics?

Was it helpful?

Solution

There are many ways to skin a cat, but the path of least resistance here is going to be making the constructors of your various part types public or internal.

OTHER TIPS

You can't do it, except for putting them in their own assembly and use the internal access specifier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top