Have the following structure
[Serializable]
public class Parent
{
public int x = 5;
}
[Serializable]
public class Child : Parent
{
public HashAlgorithm ha; //This is not Serializable
}
I want to serialize this using the following code:
public class Util {
static public byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
{
return null;
}
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
I am working with objects of type Child in my code, however, I have a field within the Child object that is non-serializable (for example: HashAlgorithm). Hence, I attempted the convert to type Parent using the below code:
public byte[] tryToSerialize(Child c)
{
Parent p = (Parent) c;
byte[] b = Util.ObjectToByteArray(p);
return b;
}
However, this returns the error that HashAlgorithm is not serializable, despite trying to serialize the child which does not include this field. How can I accomplish what I need?
This is not possible.
You cannot serialize a class as one of its base classes.
Instead, add
[NonSerialized]to the field.