0

I have a Class MyClass which implements is Serializeable to XML, I use this to simply persist the data.

Now I need to implement a Copy-Constructor and every Field that needs to be copied is also beeing serialized, so it'd be the most easy way to achieve my solution.

This is what i've tried so far

    static public MyClass Clone(MyClass MyClass)
    {
        MyClass clone;
        XmlSerializer ser = new XmlSerializer(typeof(MyClass), _xmlAttributeOverrides);
        using (var ms = new MemoryStream())
        {
            ser.Serialize(ms, MyClass);
            clone = (MyClass)ser.Deserialize(ms);
        }
        return clone;
    }

It using the serialisation Funcions of the XmlSerializer does work when im using a FileStream but in this case I get an InvalidOperationException in the Deserialize(Stream)-Method.

Stack trace

   bei System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   bei System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
   bei Namespace.MyClass.Clone(MyClass myClass)

I've never been using a MemoryStream before, but here microsoft tells me I can use this Stream with serialisation.

Tell me what I'm not seeing :)

LuckyLikey
  • 3,504
  • 1
  • 31
  • 54

1 Answers1

2

Before

clone = (MyClass)ser.Deserialize(ms);

add:

ms.Position = 0;

You could also implement a Cloning functionality so that you don't need to serialize/deserialize an xml to some stream.

Andrei Tătar
  • 7,872
  • 19
  • 37
  • Thanks this works. I know there are several possibilities for doing this. [here](http://stackoverflow.com/questions/78536/deep-cloning-objects) I've read a lot about this. – LuckyLikey Apr 20 '15 at 13:37