I have a question about binary serialization in C#
I need to be able to deep clone objects of class B (along with all it's subobjects in the graph of course). I'd like to implement this by using binary serialization. The discussion if that's the best method is irrelevant in the context of this question.
Say I have this class structure:
public class A
{
private B objB;
}
[Serializable]
public class B : ICloneable
{
private C objC1;
private C objC2;
public object Clone()
{
B clone = Helper.Clone<B>(this);
return (B)clone;
}
}
[Serializable]
public class C
{
int a;
int b;
}
The helper class for deep cloning with binary serialization (I got this method code from somewhere on the net, don't really remember where TBH, but it looks alright)
public static class Helper
{
public static T Clone<T>(T OriginalObject)
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, OriginalObject);
objectStream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(objectStream);
}
}
}
So at some point in my app, I hit following code:
B clone = (B)objA.objB.Clone();
The problem is that the debugger moans about class A not being marked as Serializable.
But I don't want to serialize A, I want to serialize B and it's subobject C.
I guess it tries to serialize the parent object A too, because it's all interconnected in the object graph. But is there any way I can exclude it from being serialized at this point?