I am trying to serialize my own enum with the binaryformatter, but i keep getting an error that says that there is no assembly id. My enum looks like this:
[Serializable]
public enum MyEnum{NONE, OPTION1, OPTION2, OPTION3};
This is my code for the serializing:
public class Binder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
return Type.GetType(typeName);
}
public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
assemblyName = "";
typeName = serializedType.FullName;
}
}
public static byte[] GetBytes<T>(this T c)
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream m = new MemoryStream())
{
bf.Binder = new Binder();
bf.Serialize(m, c);
return m.ToArray();
}
}
The full error:
Exception thrown: 'System.Runtime.Serialization.SerializationException' in mscorlib.dll An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll No assembly ID for object type 'program.MyEnum'.
Because the error states:
No assembly ID for object type 'program.MyEnum'.
The assemblyName
parameter of BindToName
seems suspect.
A quick search didn't turn up a lot, except this does mention:
...if you leave the assembly-name as NULL, the normal assembly name will be written into the stream, which is why we set a non-null value (you could use a zero-length string)
So I assume that setting assemblyName
to null
, rather than an empty string, would cause the Binding to resolve to the current (normal?) assembly.