views:

49

answers:

1

I am currently using Serialization in order to make deep copies of some autogenerated webservice class. Is a cleaner way to do this? The classes are autogenerated, so I don't want to touch them. More detail:

My current, code (which works fine) is this:

using (Stream stream = new MemoryStream()) //Copy IR
{
    IFormatter IF = new BinaryFormatter();
    IF.Serialize(stream, IR);
    stream.Seek(0, SeekOrigin.Begin);
    IR2 = (ObjectType)IF.Deserialize(stream);
}

The code is being used to copy an automatically generated class. When I added a webreference to a soap request, Visual Studio 2005 automatically generated this class, among others. The classes look something like this:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3074")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace=/*"[WebServiceNameSpace]"*/)]
public partial class ObjectType {

    private string AField;        
    private string BField;
    //...
    public string A {
        get {
            return this.AField;
        }
        set {
            this.AField = value;
        }
    }

    /// <remarks/>
    public string B {
        get {
            return this.BField;
        }
        set {
            this.BField = value;
        }
    }
    //...
}
+2  A: 

Deep cloning is painful. If the classes support serialization, that is the best (=most reliable) option. Anything else is lots of work.

Actually, since the types support xml serialization, the natural choice here would be XmlSerializer.

Is there a problem you want to solve? Performance?

Marc Gravell
No, there is no problem I am trying to solve. Just trying to see if there is a cleaner way to do it. I'm not particularly surprised that there isn't, but thought I'd ask. (I realize It would be easy enough to move that serialization code to a separate generic function or whatever, but that doesn't make anything cleaner.)
Brian