title: C#: Returning 'this' for method nesting?
body: <p>I have a class that I have to call one or two methods a lot of times after each other. The methods currently return <code>void</code>. I was thinking, would it be better to have it return <code>this</code>, so that the methods could be nested? or is that considerd very very very bad? or if bad, would it be better if it returned a new object of the same type? Or what do you think? As an example I have created three versions of an adder class:</p>
  
  <pre><code>// Regular
  class Adder
  {
      public Adder() { Number = 0; }
  
      public int Number { get; private set; }
  
      public void Add(int i) { Number += i; }
      public void Remove(int i) { Number -= i; }
  }
  
  // Returning this
  class Adder
  {
      public Adder() { Number = 0; }
  
      public int Number { get; private set; }
  
      public Adder Add(int i) { Number += i; return this; }
      public Adder Remove(int i) { Number -= i; return this; }
  }
  
  // Returning new
  class Adder
  {
      public Adder() : this(0) { }
      private Adder(int i) { Number = i; }
  
      public int Number { get; private set; }
  
      public Adder Add(int i) { return new Adder(Number + i); }
      public Adder Remove(int i) { return new Adder(Number - i); }
  }
  </code></pre>
  
  <p>The first one can be used this way:</p>
  
  <pre><code>    var a = new Adder();
      a.Add(4);
      a.Remove(1);
      a.Add(7);
      a.Remove(3);
  </code></pre>
  
  <p>The other two can be used this way:</p>
  
  <pre><code>    var a = new Adder()
          .Add(4)
          .Remove(1)
          .Add(7)
          .Remove(3);
  </code></pre>
  
  <p>Where the only difference is that <code>a</code> in the first case is the <code>new Adder()</code> while in the latter it is the result of the last method.</p>
  
  <p>The first I find that quickly become... annoying to write over and over again. So I would like to use one of the other versions.</p>
  
  <p>The third works kind of like many other methods, like many String methods and IEnumerable extension methods. I guess that has its positive side in that you can do things like <code>var a = new Adder(); var b = a.Add(5);</code> and then have one that was 0 and one that was 5. But at the same time, isn't it a bit expensive to create new objects all the time? And when will the first object die? When the first method returns kind of? Or?</p>
  
  <p>Anyways, I like the one that returns <code>this</code> and think I will use that, but I am very curious to know what others think about this case. And what is considered best practice.</p>