title: How to prevent recursion
body: <p>Given the class named <code>OrderInfo</code>, what's the best way to ensure other developers (including myself) do not accidentally make the recursive error shown here:</p>
  
  <pre><code>public class OrderInfo : ICollection&lt;UnitModule&gt; {
  
    // Other code for class...
  
    public bool Changed { get; private set; }
  
    public void Save() {
      Save(this); // I want the static method to handle saving the data
    }
  
    public static void Save(OrderInfo item) {
      for (int i = 0; i &lt; item.Count; i++) {
        if (item[i].Changed) {
          item[i].Save();
        }
      }
      if (item.Changed) {
        item.Save(); // this would be bad!
        // Instead, all of the other developers should have to call the
        // Database Save method.
        // Is there a way to ensure this happens or do I have to rely on
        // everyone remembering this?
      }
    }
  
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> Using the marked answer, I can write my class as follows (why does not matter - this simply prevents the recursion):</p>
  
  <pre><code>public class OrderInfo : ICollection&lt;UnitModule&gt; {
    // Other code for class...
    bool saving; // &lt;= new variable
    public bool Changed { get; private set; }
  
    public void Save() {
      if (!saving) {
        Save(this);
      } else {
        throw new Exception("This item is already being saved.");
      }
    }
  
    public static void Save(OrderInfo item) {
      item.saving = true;
      try {
        for (int i = 0; i &lt; item.Count; i++) {
          if (item[i].Changed) {
            item[i].Save();
          }
        }
        if (item.Changed) {
          // item.Save(); &lt;= NOTE: this would throw an exception
          DataAccess.Save(item);
          item.Changed = false;
        }
      } finally {
        item.saving = false;
      }
    }
  }
  </code></pre>