Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
GetObjectToSerialize Method

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.6, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
© 2015 Microsoft