user232945
user232945

Reputation:

.Net Binary Serialization inheritance

In a C# Context, I have a Class B which is marked as Serializable and who's inheriting form a Class A who's not marked as this. Can i find a way to serialize instance of B without marking A as serializable?

Upvotes: 1

Views: 1544

Answers (2)

ram
ram

Reputation: 11626

Try using a serialization surrogate. Nice article by Jeff Richter

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064054

I think if you do custom serialization this should work - i.e. implement ISerializable. Not a nice option, though:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class A {
    public int Foo { get; set; }
}
[Serializable]
class B : A, ISerializable {
    public string Bar { get; set; }
    public B() { }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
        info.AddValue("Foo", Foo);
        info.AddValue("Bar", Bar);
    }
    private B(SerializationInfo info, StreamingContext context) {
        Foo = info.GetInt32("Foo");
        Bar = info.GetString("Bar");
    }    
}
static class Program {
    static void Main() {
        BinaryFormatter bf = new BinaryFormatter();
        B b = new B { Foo = 123, Bar = "abc" }, clone;
        using (MemoryStream ms = new MemoryStream()) {
            bf.Serialize(ms, b);
            ms.Position = 0;
            clone = (B)bf.Deserialize(ms);
        }
        Console.WriteLine(clone.Foo);
        Console.WriteLine(clone.Bar);
    }
}

Do you just want to store the data? I can also think of a way to do this using protobuf-net (rather than BinaryFormatter, which I assume you are using).

Upvotes: 0

Related Questions