DeSerialization doesn't work though i Implement GetObjectData method and Constructor
- by Punit Singhi
Hi,
I have a static generic dictionary in a class. As static memeber cannot serialized so i have implented ISerializable interface and method GetObjectData to serialize. I have a constructor which will also accept SerializationInfo and StreamingContext to deserliaze the dictionay. Now when i try to serialize and deserialize , it always return 1(thoug i added 2 entries). please find the pseduo code-
[Serializable]
public class MyClass : ISerializable
{
internal static Dictionary<long, string> dict = new Dictionary<long,string>();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("static.dic", MyClass1.dict, typeof(Dictionary<long, string>));
}
public MyClass(SerializationInfo info, StreamingContext context)
{
MyClass.dict= (Dictionary<long, string>)info.GetValue("static.dic",
typeof(Dictionary<long, string>));
}
public void Add()
{
dict.Add(21, "11");
}
public MyClass()
{
dict.Add(21, "11");
}
}
public class MyClass
{
MyClass myClass = new MyClass();
public static void Main()
{
myClass.Add();
FileStream fileStream = new FileStream("test.binary", FileMode.Create);
IFormatter bf = new BinaryFormatter();
bf.Serialize(fileStream, myClass);
fileStream.Dispose();
fileStream.Close();
fileStream = new FileStream("test.binary", FileMode.Open);
bf = new BinaryFormatter();
myClass = (MyClass1)bf.Deserialize(fileStream);
}
}