C# - Keep track of auto incrementing variable between serialization and
deserialization
I am working on a project and need help with regards to auto incrementing
ID fields.
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.
For instance...
[Serializable]
class Category
{
private static int iCatID = 0;
private int iCategoryID;
private string sCategory;
public Category(string _sCategory)
{
iCatID++;
sCategory = _sCategory;
}
}
I learnt the hard way that after creating 5 or so instances of this class,
I serialized it, then deserialized and expected iCatID 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.
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?
I've thought of two ways to possibly do it:
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.
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.
I'm sure that there's a more elegant way of dealing with this.
Any help would be great, thanks.
No comments:
Post a Comment