Search code examples
c#web-servicesserializationclone

Cleaner way to deep copy an AutoGenerated WebService Class


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;
        }
    }
    //...
}

Solution

  • 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?