user2620088
user2620088

Reputation: 29

C# - Setting default int value in BinaryFormatter deserialization

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

Upvotes: 2

Views: 498

Answers (2)

Pavel Sem
Pavel Sem

Reputation: 1753

[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
}

Upvotes: 2

ElConrado
ElConrado

Reputation: 1640

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;
}

Upvotes: 0

Related Questions