One of the solutions in our company consumes a 3rd party service. Communication is done through XML messaging. On our end, we generate classes to be used based on XML sche
You can handle this situation with ISerializable
, however you will need to loop through the deserialized properties using SerializationInfo.GetEnumerator to determine what type of data was actually read from the stream. In addition, you need to be aware that BinaryFormatter
serializes fields not properties, so if your class used Auto-Implemented Properties then the name previously stored in the binary stream will be the name of the backing field not the name of the property.
For instance, say this is your original class:
[Serializable]
public class Foo
{
public bool Bar { get; set; }
public Foo() { }
}
Now you want to change Bar
to an integer. To serialize or deserialize both old and new BinaryFormatter
streams, use the following implementation of ISerializable
:
[Serializable]
public class Foo : ISerializable
{
public int Bar { get; set; }
public Foo() { }
public Foo(SerializationInfo info, StreamingContext context)
{
var enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
Debug.WriteLine(string.Format("{0} of type {1}: {2}", current.Name, current.ObjectType, current.Value));
if (current.Name == "Bar" && current.ObjectType == typeof(int))
{
Bar = (int)current.Value;
}
else if (current.Name == "<Bar>k__BackingField" && current.ObjectType == typeof(bool))
{
var old = (bool)current.Value;
Bar = (old ? 1 : 0); // Or whatever.
}
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Bar", Bar);
}
}
If we convert boolean to integer, that would be either 0 or 1. Can you please try:
int val=int.Tryparse(myBooleanValue);
Or
int val= myBooleanValue?1:0;