- Home /
Serialize a HashSet for BinaryFormatter using Surrogate
I am using surrogates to convert non-serializable stuff like Vector3, Quaternion to use for BinaryFormmater. I have also a HashSet that stores unique neighbors of the Node class itself. These form a graph object that I want to use for persisting.
.
So far, the file writing works, but the serialization of HashSet is not implemented (using UnityEditor 5.6.0f3) and as discussed here. Converting to Array seems not suitable for me, because I want to use explicitely HashSet functionality without any extra allocation.
.
I am unsure if the same approach will be working, just like Vector3 / Quaternion as it deals with a type parameter.
.
Here is what I have so far.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class SerializableHashSet<T> : HashSet<T>, ISerializationSurrogate
{
// Method called to serialize a HashSet<T> object
public void GetObjectData(System.Object obj, SerializationInfo info, StreamingContext context)
{
HashSet<T> hashset = (HashSet<T>)obj;
info.AddValue("hashset", hashset);
}
// Method called to deserialize a HashSet<T> object
public System.Object SetObjectData(System.Object obj, SerializationInfo info, StreamingContext context,ISurrogateSelector selector)
{
HashSet<T> hashset = info.GetValue("hashset", typeof(HashSet<T>));
obj = hashset;
return obj;
}
}
Can you not just use a dictionary ins$$anonymous$$d?
Edit: Oh wait am I thinking of a HashTable, which are serialisable anyway.
Your answer
![](https://koobas.hobune.stream/wayback/20220612222510im_/https://answers.unity.com/themes/thub/images/avi.jpg)