Edit

Share via


IDataContractSurrogate.GetObjectToSerialize(Object, Type) Method

Definition

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

C#
public object GetObjectToSerialize(object obj, Type targetType);

Parameters

obj
Object

The object to substitute.

targetType
Type

The Type that the substituted object should be assigned to.

Returns

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.

Examples

The following example shows an implementation of the GetObjectToSerialize method.

C#
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;
    }

Remarks

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

Applies to

Product Versions
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1