This documentation is archived and is not being maintained.

IDataContractSurrogate.GetObjectToSerialize Method

During serialization, returns an object that substitutes the specified object.

Namespace:  System.Runtime.Serialization
Assembly:  System.Runtime.Serialization (in System.Runtime.Serialization.dll)

Object GetObjectToSerialize(
	Object obj,
	Type targetType


Type: System.Object
The object to substitute.
Type: System.Type
The Type that the substituted object should be assigned to.

Return Value

Type: System.Object
The substituted object that will be serialized. The object must be serializable by the DataContractSerializer. For example, it must be marked with the DataContractAttribute attribute or other mechanisms that the serializer recognizes.

This method must not return null because on deserialization the data will be cast to type Object and an InvalidCastException is thrown.

The following example shows an implementation of the GetObjectToSerialize method.

public object GetObjectToSerialize(object obj, Type targetType)
        Console.WriteLine("GetObjectToSerialize Invoked");
        Console.WriteLine("\t type name: {0}", obj.ToString());
        Console.WriteLine("\t target type: {0}", targetType.Name);
        // This method is called on serialization.
        // If Person is not being serialized...
        if (obj is Person )
            Console.WriteLine("\t returning PersonSurrogated");
            // ... use the XmlSerializer to perform the actual serialization.
            PersonSurrogated  ps = new PersonSurrogated();
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            StringWriter sw = new StringWriter();
            xs.Serialize(sw, (Person)obj );
            ps.xmlData = sw.ToString();
            return ps;
        return obj;


.NET Framework

Supported in: 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.