2

I had the following class:

[Serializable]
public class Message
{  public string messageSummary;
   public DateTime messageDate;
}

Later, i decided to add to the class another int field - messageNumber

[Serializable]
public class Message
{  
    public string messageSummary;
    public DateTime messageDate;
    public int messageNumber;
}

In deserialization, when deserializing an old serialized Message class(without messageNumber field) - how can I set the default value of messageNumber to -1 instead of 0?

I tried to define a method with [OnDeserialized()] attribute, but messageNumber is already set there to 0. 0 can also the value of messageNumber, so I can't override it in that method. Is it possible to set the default value to -1? Thanks

mybrave
  • 1,662
  • 3
  • 20
  • 37
  • Why don't you used DefaultValueAttribute https://stackoverflow.com/questions/2329868/net-defaultvalue-attribute ? In your case is it posiible to use properties instead of fields? – ElConrado Mar 30 '20 at 11:21

2 Answers2

2

[OnDeserialized] happens after deseralization. If you want to set default value you can define [OnDeserializing] serialization callback

[OnDeserializing]
private void SetMessageNumberDefault(StreamingContext sc)
{
    messageNumber = -1;     // add default value
}
mybrave
  • 1,662
  • 3
  • 20
  • 37
0

You can try DefaultValueAttribute as describe in this documentation. Than you can try solution as follow:

[Serializable]
public class Message
{
    public const int Int_Default = -1;
    public string messageSummary;
    public DateTime messageDate;
    [System.ComponentModel.DefaultValue(Int_Default)]
    public int messageNumber { get; set; } = Int_Default;
}
ElConrado
  • 1,477
  • 4
  • 20
  • 46