Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference a code

Tags:

c#

.net

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!

like image 787
Vadim Avatar asked Dec 07 '25 17:12

Vadim


1 Answers

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();
like image 94
Groo Avatar answered Dec 09 '25 07:12

Groo



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!