Is it possible to return the child class through a method in the parent class?

3

I am doing a builder and would like it to have the following behavior:

abstract class ClassePaiBuilder
{
    public ClassePaiBuilder SetAtributo(string atributo)
    {
        // codigo
        return this;
    }

    public string Build()
    {
        string result = "";
        //processo os atributos e gero uma string
        return result;
    }
}

class ClasseFilhaBuilder : ClassePaiBuilder
{
    public ClasseFilhaBuilder SetOutroAtributo(string outroAtributo)
    {
        // codigo
        return this;
    }
}

class Program
{
    public void Run()
    {
        string valorQualquer = new ClasseFilhaBuilder()
            .SetAtributo("atributo da classe pai")
            .SetOutroAtributo("atributo da classe filha")
            .Build();
    }
}

Is it possible? In this case, the compilation is breaking down because in SetAtributo I am returning the instance typed as ClassePaiBuilder , which does not have the SetOutroAtributo method.

    
asked by anonymous 16.10.2015 / 02:13

1 answer

2

The best I could think of not to create a meaningless dependency was this:

abstract class ClassePaiBuilder<T> where T : ClassePaiBuilder<T> {
    public T SetAtributo(string atributo) {
        // codigo
        return (T)(object)this;
    }

    public object Build() {
        return new object();
    }
}

class ClasseFilhaBuilder : ClassePaiBuilder<ClasseFilhaBuilder> {
    public ClasseFilhaBuilder SetOutroAtributo(string outroAtributo) {
        // codigo
        return this;
    }
}

public class Program {
    public void Main() {
        new ClasseFilhaBuilder()
            .SetAtributo("atributo da classe pai")
            .SetOutroAtributo("atributo da classe filha")
            .Build();
    }
}

See running on dotNetFiddle .

The generic type is being used to communicate the parent class which is the type that should be used to convert the this . And obviously it has the restriction to allow only derived types to be used in the conversion.

It's not a wonderful solution, but it works. Think about whether this is worth doing.

    
16.10.2015 / 02:35