Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast when chaining methods in C#

Tags:

syntax

c#

casting

I'm trying to code something, and I always return the object itself so I can keep chaining. Like this

object.SetThis().SetThat().SetThisThirdThing().setThisFourthThing();

I return this in all my methods so I can keep doing this. But one of my methods is something I made in my base class, which of course then returns the base class.

So instead of public MyClass SetThat() it returns public SuperClass SetThat(). And because it returns SuperClass and not MyClass I can't call SetThisThirdThing() because the base class doesn't know about it.

So how do I cast it so I can keep the chain? What is the syntax? I tried

object.SetThis().(MyClass)SetThat().SetThisThirdThing().setThisFourthThing();

Or is there a way to make a superClass method return the subclass when called from the subclass without having to override it in all the subclasses?

This is one of the things that all the subclasses have in common, so it would be really nice if I would be able to circumvent this somehow without having to override it in all my subclasses.

like image 210
Hafax Avatar asked Oct 21 '25 00:10

Hafax


2 Answers

is there a way to make a superClass method return the subclass when called from the subclass without having to override it in all the subclasses?

Can you make the superclass generic?

public class SuperClass<T> where T: SuperClass<T>
{
    public T SetThis()
    {
        ....
        return (T)this;
    }
}

public class SubClass : SuperClass<SubClass>
{
}

Note that it's not 100% guaranteed since you could also do this:

public class EvilSubClass : SuperClass<SubClass>
{
}

which fits the generic contraints, but now the return type of SetThis() is SubClass and not EvilSubClass

like image 140
D Stanley Avatar answered Oct 23 '25 14:10

D Stanley


Try like this:

((MyClass)object.SetThis().SetThat()).SetThisThirdThing()
like image 44
Nevca Avatar answered Oct 23 '25 14:10

Nevca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!