Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement method chaining?

In C# how does one implement the ability to chain methods in one's custom classes so one can write something like this:

myclass.DoSomething().DosomethingElse(x); 

etc...

Thanks!

like image 900
Tony The Lion Avatar asked Jan 13 '10 09:01

Tony The Lion


People also ask

How do you do chaining method?

Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).

Why do we do method chaining?

Applications of Method Chaining It is used to implement method cascading. It is also used to implement in fluent interfaces.


1 Answers

Chaining is a good solution to produce new instance from existing instances:

public class MyInt
{
    private readonly int value;

    public MyInt(int value) {
        this.value = value;
    }
    public MyInt Add(int x) {
        return new MyInt(this.value + x);
    }
    public MyInt Subtract(int x) {
        return new MyInt(this.value - x);
    }
}

Usage:

MyInt x = new MyInt(10).Add(5).Subtract(7);

You can also use this pattern to modify an existing instance, but this is generally not recommended:

public class MyInt
{
    private int value;

    public MyInt(int value) {
        this.value = value;
    }
    public MyInt Add(int x) {
        this.value += x;
        return this;
    }
    public MyInt Subtract(int x) {
        this.value -= x;
        return this;
    }
}

Usage:

MyInt x = new MyInt(10).Add(5).Subtract(7);
like image 158
dtb Avatar answered Nov 02 '22 04:11

dtb