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

Asked

Viewed 811 times

3

I’m making a Builder and I’d like you to behave as follows:

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 because in the SetAtributo I’m returning the instance typed as ClassePaiBuilder, who does not have the method SetOutroAtributo.

  • Those return this so sure? Or was this just for example?

  • Yes @jbueno, you’re right.

  • Okay. But what’s the point of this? The code on Run() doesn’t make sense.

  • The goal can be anything, imagine that at the end I will generate a string. I edited to try to improve the example

1 answer

2


The best I could think of to not 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();
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Generic type is being used to communicate the parent class which type should be used to convert the this. And it obviously has the constraint to allow only derivative types of it to be used in the conversion.

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

  • Thank you very much, it worked :D in my case I created some Builders that generate strings, with the same parameters, but with different results, including having other parameters. In this case, I wanted to center the repeated parameters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.