I have a class like this:
public class Foo
{
public IBar {get;set;}
//tons of other properties
}
public interface IBar
{
//whatever
}
The class is used for binary serialization (standard use of BinaryFormatter). An implementation of IBar is marked with [Serializable] so everything works.
Now I want not to serialize Bar and preserve backwards compatibility (it was not referenced in the code anyway). NonSerialized attribute seems to be enough. However it can be applied only to fields, not to automatic properties. So I tried this:
public class Foo
{
private IBar _bar;
[NonSerializable]
public IBar Bar
{
get { return _bar; }
set { _bar = value; }
}
}
Suprisingly it works well - I can both deserialize old Foos and the new ones.
My question is: how can it possibly work if these are the fields that are serialized and the automatic property's backing field is likely to have some non-C# characters in its name?
In other words:
Old Foo's IBar field name (my guess): k__BackingField
New Foo's IBar field name: _bar
Obviously they don't match, so how BinaryFormatter overcomes this?