c# - Default values only for unset properties when deserializing -


i have little problem, i'm guessing should have been solved better code design beginning. here am.

i have app pretty large user base. app uses profiles. profiles are deserialized file when starting app.

in new releases profile class gets new properties. if profile deserialized older version these properties uninitialized. have set default values if profile created current version of app.

is there simple way of initializing property default value if serialized version doesn't have it?

you can specify method run after deserializing set default values:

using system.runtime.serialization;  [serializable] class car {     public int id { get; set; }     public string make { get; set; }     public int doors { get; set; }      public string foo { get; set; }    // added property      ...     [ondeserialized()]     internal void ondeserializedmethod(streamingcontext context)     {         if (string.isnullorempty(this.foo))             this.foo = "ziggy";     } } 

you might want consider protobuf-net data contract binary serializer. more flexible these things, more options, faster , creates smaller output. double checked sure, , protobuf not undo fields doesnt have information for. so:

[protocontract] class car {     [protomember(1)]     public int id { get; set; }     [protomember(2)]     public string make { get; set; }     [protomember(3)]     public int doors { get; set; }     [protomember(4)]     public string foo { get; set; }      // new prop      public car()     {         this.foo = "ziggy";     }     ...  } 

if there no serialized value foo, old value ctor retained. initialize new properties there , not have worry them getting reset null. if have lot of properties bitmap, font , rectangle might want stay binaryformatter.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -