Live Chat Icon For mobile
Live Chat Icon

While deserializing how do I check whether a name is available in the deserialized info?

Platform: WinForms| Category: General IO

This is usually an issue when a newer version introduces newer names, then the older version will not serialize property due to the absence of certain names. For example, this code will fail, sometimes:


protected MyClassConstructor(SerializationInfo info, StreamingContext context)
{
	...
	// This might fail if MyProp was added in a newer version and you are serializing an older version.
	this.MyProp = info.GetBoolean('MyProp');
}

To avoid such conflicts, you could insert version nos. into the serialized info. and during deserialization check for a name only when a particular version is being deserialized. Or you could instead parse through the available info in the SerializationInfo list as follows:


[C#]
protected MyClassConstructor(SerializationInfo info, StreamingContext context)
{
	foreach(SerializationEntry entry in info)
	{
		switch(entry.Name)
		{
			case 'MyProp':
			// This will make sure that older versions without the MyProp name will also deserialize without any problems
			this.MyProp = (bool)entry.Value;
			break;
			...
		}
	}

}

[VB.Net]
Protected MyClassConstructor(ByVal info As SerializationInfo, ByVal context As StreamingContext) As Protected
	Dim entry As SerializationEntry
	For Each entry In info
		Select Case entry.Name
			Case 'MyProp'
			’ This will make sure that older versions without the MyProp name will also deserialize without any problems
			Me.MyProp = (Boolean)entry.Value
			Exit For
 
		End Select
	Next
 
End Function

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.