Export (0) Print
Expand All

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
)

Parameters

obj
Type: System.Object

The object to substitute.

targetType
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.5.2, 4.5.1, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Show:
© 2014 Microsoft