This static class provides methods for Serializing and Deserializing .NET objects which are marked up using the .NET Data Contracts in WCF. This is new feature from .NET 3.0 onwards and provides a more optimal and controlled method compared to XmlObjectSerialisation XmlObjectSerialisation Once the Data Contracts have been marked up they can be taken down a string for persistent storage or transport over the wire.

Namespace:  CA.Common.xml
Assembly:  CA.Common (in CA.Common.dll) Version: 1.0.0.0 (1.0.0.0)

Remarks

Full source code provided below

CopyFull Source Code for the DataContractSerialisation class
//Source code from the Code Associate C# code library, Full documentation and latest updates can be found
//@ http://www.codeassociate.com/caapi/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace CA.Common.xml
{
    public static class DataContractSerialisation
    {
        public static string SerialiseObject(object obj)
        {
            return SerialiseObject(obj, null);
        }

        public static string SerialiseObject(object obj, List<Type> knownTypes)
        {
            DataContractSerializer ser = new DataContractSerializer(obj.GetType(), knownTypes);
            StringBuilder sb = new StringBuilder();
            StringWriter writer1 = new StringWriter(sb);
            XmlTextWriter writer = new XmlTextWriter(writer1);
            ser.WriteObject(writer, obj);
            return (sb.ToString());
        }


        public static object DeSerialiseObject(string obj, Type t, List<Type> knownTypes)
        {
            DataContractSerializer ser = new DataContractSerializer(t, knownTypes);
            StringReader reader1 = new StringReader(obj);
            XmlTextReader reader = new XmlTextReader(reader1);
            return (ser.ReadObject(reader));
        }


        public static T DeSerialiseObject<T>(string obj, List<Type> knownTypes)
        {
            return (T) DeSerialiseObject(obj, typeof (T), knownTypes);
        }

        public static T DeSerialiseObject<T>(string obj)
        {
            return DeSerialiseObject<T>(obj, null);
        }

    }
}

Inheritance Hierarchy

System..::.Object
  CA.Common.xml..::.DataContractSerialisation

See Also