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);
source share