9

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!

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

4 Answers4

17

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);
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    +1 For the good example. Generally this concept is referred to as a Fluent Interface - see http://en.wikipedia.org/wiki/Fluent_interface. Though technically you aren't using one, but it would be trivial to introduce one. – Wim Jan 13 '10 at 10:02
1

DoSomething should return a class instance with the DoSomethingElse method.

jmservera
  • 6,454
  • 2
  • 32
  • 45
1

For a mutable class, something like

class MyClass
{
    public MyClass DoSomething()
    {
       ....
       return this;
    }
}
H H
  • 263,252
  • 30
  • 330
  • 514
0

Your methods should return this or a reference to another (possibly new) object depending on exactly what you want to acheive

jk.
  • 13,817
  • 5
  • 37
  • 50