Serialization is about instances... if you took a snapshot then it would be stored, i.e.
static int nextCatID;
private readonly int catID;
private string category;
...
public Category(string category)
{
catID = Interlocked.Increment(ref nextCatID);
this.category = category
}
here catID
is the value related to the individual instance - and would be serialized and deserialized; of course, it could then lead to repeats: if you serialize item 1 and then deserialize it 5 times, you'll have 5 more "item 1"s.
If you wanted the value to be set during deserialization, you can do that too - just mark the field as non-serialized:
static int nextCatID;
[NonSerialized]
private int catID;
and set it in a post-serialization callback using the same code from the constructor (note that because the callback is not a constructor, you can't use readonly
):
[OnDeserialized()]
private void OnDeserialized(StreamingContext context)
{
catID = Interlocked.Increment(ref nextCatID);
}