I'm wondering if this is possible to do in c#.
Let's say i have a class with these methods:
public class Ladder
{
private int currentStep = 0;
Ladder Up()
{
currentStep++;
return this;
}
Ladder Down()
{
currentStep--;
return this;
}
}
I can use it like this:
Ladder ladder = new Ladder();
ladder.Up().Up().Up().Down().Down();
Now, I would like to add a conditional method, that could be used like this:
ladder.IF(somecondition, Up(), Down());
Meaning if somecondition == true then execute Up(), else Down()
Is it possible to do? I was thinking about using anonymous methods, but can't figure out how to reference "this" instance so it would know what that these functions are referred to.
Any help is greatly appreciated!
This would probably be close to what you're asking, although I wouldn't say it will make the code clearer to future maintainers:
Ladder If(bool condition,
Func<Ladder, Ladder> @true,
Func<Ladder, Ladder> @false)
{
return condition ? @true(this) : @false(this);
}
Usage:
ladder
.Up()
.Down()
.If(true, l => l.Up(), l => l.Down())
.Up()
.Down();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With