DarkNik
DarkNik

Reputation: 823

Return child class in parent method C#

I have parent class:

public abstract class ParentClass
{
     public ParentClass ParentMethod() { ... }
}

Also I have two childs:

public class ChildA : ParentClass
{
    public ChildA ChildAMethod1()
    {
        ... 
        return this; 
    }

    public ChildA ChildAMethod2()
    {
        ... 
        return this; 
    }
}

public class ChildB : ParentClass
{
     public ChildB ChildBMethod() { ... 
            return this; }
}

In this case I have possibility to write like this:

new ChildA().ChildAMethod1().ChildAMethod2();

But how to implement possibility to write like this:

new ChildA().ParentMethod().ChildAMethod1().ChildAMethod2();

new ChildB().ParentMethod().ChildBMethod1();

Is there any other patterns to such possibility?

Upvotes: 5

Views: 3053

Answers (2)

Zoran Horvat
Zoran Horvat

Reputation: 11301

What is the connection between parent and child class if methods of the child are not inherited from parent?

Since classes are already decoupled, you can emphasize that decoupling via an interface:

public interface INext
{
    INext ChildAMethod1();
    INext ChildAMethod2();
}

public abstract class ParentClass
{
    public INext ParentMethod()
    {
        ...
        return new ChildA(...);
    }
}

public class ChildA : ParentClass, INext
{
    public INext ChildAMethod1()
    {
        ... 
        return this; 
    }

    public INext ChildAMethod2() 
    {
        ... 
        return this; 
    }
}

Upvotes: 0

Ivan Zaruba
Ivan Zaruba

Reputation: 4504

Make ParentMethod generic

public abstract class ParentClass
{
    public T ParentMethod<T>() where T:ParentClass
    {
        return (T)this; 
    }
}

then call it like

new ChildA().ParentMethod<ChildA>().ChildAMethod1().ChildAMethod2();
new ChildB().ParentMethod<ChildB>().ChildBMethod1();

Upvotes: 4

Related Questions