title: C# - Keep track of auto incrementing variable between serialization and deserialization
body: <p>I am working on a project and need help with regards to auto incrementing ID fields. </p>
  
  <p>In terms of serialization, what is the best way to get the ID from when it was last serialized when it comes to deserialization of a static variable that you have been auto incrementing upon each instantiation of a class.</p>
  
  <p>For instance...
  </p>
  
  <pre><code>[Serializable]
  class Category
  {
      private static int iCatID = 0;
      private int iCategoryID;
      private string sCategory;
  
      public Category(string _sCategory)
      {
          iCatID++;
          iCategoryID = iCatID;
          sCategory = _sCategory;
      }
  }
  </code></pre>
  
  <p>I learnt the hard way that after creating 5 or so instances of this class, I serialized it, then deserialized and expected <code>iCatID</code> to pick up where it left off when I started creating more instances of the class, but it had of course reset back to 0.</p>
  
  <p>What I want to know is how do I keep track of an auto incrementing variable in between serialization and deserialization and what would be best practice?</p>
  
  <p>I've thought of two ways to possibly do it:</p>
  
  <ol>
  <li>When serializing the class, save the value of the static variable to a global setting and get that value again and set the static variable from the global setting on deserialization.</li>
  <li>When deserializing the class, use linq to query all instances of the class and get the highest number and then set the static variable accordingly.</li>
  </ol>
  
  <p>I'm sure that there's a more elegant way of dealing with this. </p>
  
  <p>Any help would be great, thanks.</p>