How to implement a chain of methods?

In C #, how to implement the chaining function in one user class so that you can write something like this:

myclass.DoSomething().DosomethingElse(x); 

etc...

Thanks!

+4
source share
4 answers

Chains are a good solution to create a 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); } } 

Using:

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

You can also use this template to modify an existing instance, but this is usually 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; } } 

Using:

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

DoSomething should return an instance of the class using the DoSomethingElse method.

+1
source

For a mutable class, something like

 class MyClass { public MyClass DoSomething() { .... return this; } } 
+1
source

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

0
source

All Articles