[KnownType] Attribute in WCF

When data is transmitted between a sender and receiver, a type needs to be found at runtime for the data arriving at the receiver. The type is looked for by searching all of the available known types. These known types are specified via the [KnownType] attribute. The [KnownType] attribute provides the ability to specify the types that should be used for deserialization, and it lets you specify these types in advance.
The [KnownType] attribute is specified in addition to the [DataContract] attribute as shown in the following example:

[DataContract]
[KnownType]
public class BuyStock
{
    ...
}

There are two properties, or parameters, that can be specified with this attribute: MethodName and Type. Both are discussed next.

MethodName

The MethodName property specifies the name of the method that contains a list of types recognized during serialization. The referenced method must be a static method, must accept no parameters, and return an array of Type objects.
In the following example, the MethodName parameter is used to specify a method:

[DataContract]
[KnownType(TypeOf(NumberTypes))]
public class BuyStock
{
    ...
}
[DataContract]
public class NumberTypes : BuyStock
{
    Public NumberTypes(double StockPrice)
    ...
}

Type

The Type property returns the type recognized by the DataContractSerializer during the serialization or deserialization process. The DataContractSerializer serializes and deserializes an instance of a type into either an XML stream or document via the data contract.

Tagged . Bookmark the permalink.

Leave a Reply