Peter
Peter

Reputation: 1715

How can I serialize base class when working with instance of derived class?

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?

Upvotes: 2

Views: 3210

Answers (2)

Zordex
Zordex

Reputation: 53

You can implement ISerializable in the base class and then just pass things from derived like:

private Child() { } // Make sure you got a public/protected one in Parent

private Child(SerializationInfo info, StreamingContext context) 
     : base(info, context) { }

After you implement ISerializable just use the Serialize method from Child.

Upvotes: 3

SLaks
SLaks

Reputation: 887315

This is not possible.
You cannot serialize a class as one of its base classes.

Instead, add [NonSerialized] to the field.

Upvotes: 4

Related Questions