Here is code sample which uses DataContractSerializer to Clone any DTO object which is used between WCF Service & Client.
It serializes source object into a XML string and then convert back sane XML string to another object of passed type.
It serializes source object into a XML string and then convert back sane XML string to another object of passed type.
public static T Clone<T>(T source) { string objectstr; using (MemoryStream memoryStream = new MemoryStream()) { DataContractSerializer serializer = new DataContractSerializer(source.GetType()); serializer.WriteObject(memoryStream, source); objectstr = Encoding.UTF8.GetString(memoryStream.ToArray()); } using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(objectstr))) { XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null); DataContractSerializer serializer = new DataContractSerializer(source.GetType()); return (T) serializer.ReadObject(reader); } }
No comments:
Post a Comment