IDataContractSurrogate.GetObjectToSerialize Method (Object, Type)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

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
Available since 3.0
Return to top