Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change auto implemented properties to normal and deserialization with BinaryFormatter

I have an object with a property implemented like

public String Bla {get;set;} 

After changing the implementation to something like

private String _bla;

public String Bla
{
    get { return _bla; }
    set { _bla = value; } 
} 

on deserialzation, this Property comes up empty.

i have lots of serialized data from the old implementation, and would like to load them with the new implementation

is there any way, to change the implentation to be compatible with older binary files?

EDIT:

Some people might run into the same problem, so here's my hackish solution:

the autogenerated fields have a naming convention that is non-valid c# code:

[CompilerGenerated]
private string <MyField>k__BackingField;

[CompilerGenerated]
public void set_MyField(string value)
{
    this.<MyField>k__BackingField = value;
}

[CompilerGenerated]
public string get_MyField()
{
    return this.<MyField>k__BackingField;
}

the quick and dirty fix for me was to create a private backing field called xMyFieldxK__BackingField in the source,

and patching the serialized binarydata by replacing all occurences of <MyField> with xMyFieldx before deserialisation

like image 237
Dr. Wummi Avatar asked Oct 22 '22 23:10

Dr. Wummi


1 Answers

Try implementing ISerializable

    [SecurityCritical]
    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
            throw new ArgumentNullException("info");

        info.AddValue("name of compiler generated field", _bla);
    }
like image 67
Henrik Avatar answered Oct 30 '22 03:10

Henrik