KnownTypeSerializationAttribute

Namespace: System.Runtime.Serialization

Assembly: System.Runtime.Serialization.dll

Summary

Specifies a known type that can be serialized or deserialized by the DataContractSerializer or DataContractJsonSerializer. This attribute is applied to a class to inform the serializer about types that might be encountered during serialization/deserialization, especially in inheritance scenarios or when using generic types.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, AllowMultiple = true)] public sealed class KnownTypeSerializationAttribute : Attribute

Constructors

public KnownTypeSerializationAttribute(Type knownType)

Initializes a new instance of the KnownTypeSerializationAttribute class with the specified known type.

Parameters:

  • knownType: The Type that represents the known type to be serialized.

Remarks

When serializing an object graph, the DataContractSerializer might encounter types that are not directly declared in the contracts of the types being serialized. In such cases, you need to inform the serializer about these potential types. The KnownTypeSerializationAttribute provides a way to do this by decorating a class or struct with the attribute, specifying the types that should be recognized and handled during serialization and deserialization.

This attribute is particularly useful when dealing with polymorphic serialization, where a base type might hold instances of derived types. By using this attribute, you ensure that the derived types are correctly serialized and deserialized even if they are not explicitly defined within the base type's data contract.

Example

[DataContract] [KnownTypeSerialization(typeof(Order))] [KnownTypeSerialization(typeof(Invoice))] public class Document { [DataMember] public int DocumentId { get; set; } } [DataContract] public class Order : Document { [DataMember] public string CustomerName { get; set; } } [DataContract] public class Invoice : Document { [DataMember] public decimal Amount { get; set; } } // Usage: var order = new Order { DocumentId = 1, CustomerName = "Alice" }; var serializer = new DataContractSerializer(typeof(Document)); // Serializing as base type using (var stream = new MemoryStream()) { serializer.WriteObject(stream, order); stream.Position = 0; var deserializedDocument = (Document)serializer.ReadObject(stream); // Deserializes as Order }

Exceptions

No specific exceptions are documented for this attribute, but standard .NET exceptions like ArgumentNullException may occur if invalid types are provided.

See Also