I'm trying to serialize a Hashset but I'm having no luck. Whenever I try to open the serialized data, I get an empty HashSet. However, a List works fine. Example code:
[Serializable()]
public class MyClass : ISerializable
{
public MyClass(SerializationInfo info, StreamingContext ctxt)
{
HashSet<string> hashset = (HashSet<string>)info.GetValue("hashset", typeof(HashSet<string>));
List<string> list = (List<string>)info.GetValue("list", typeof(List<string>));
Console.WriteLine("Printing Hashset:");
foreach (string line in hashset)
{
Console.WriteLine(line);
}
Console.WriteLine("Printing List:");
foreach (string line in list)
{
Console.WriteLine(line);
}
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
HashSet<string> hashset = new HashSet<string>();
hashset.Add("One");
hashset.Add("Two");
hashset.Add("Three");
info.AddValue("hashset", hashset);
List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");
info.AddValue("list", list);
}
}
And when run, it prints out:
Printing Hashset:
Printing List:
One
Two
Three
So the List works fine, but the HashSet comes back empty. A little stuck - can anyone see what I'm doing wrong? Thanks