views:

95

answers:

3

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!

+1  A: 

DoSomething should return a class instance with the DoSomethingElse method.

jmservera
+8  A: 

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
+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 Hollebrandse
A: 

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

jk