After reading the MSDN reference, I still have questions about when to use the KnownType attribute. I understand that the attribute communicates type information to the serializer, but when is this needed? Is it appropriate when the class being serialized has references of a base class type, and there are up-cast derivative classes that could be set to those references?
Moreover, are there any drawbacks to overusing the attribute? For instance, in the previous example, if the serialized class was marked with KnownType(baseClass) even though there was an explicit reference to that type?
The [KnownType] attribute informs the WCF service that "it is ok" to receive this Admin type because it is a subclass of the awaited UserAccount type. It is especially important when the Admin subclass has more properties, like a public string AdminEmail { get;set; } . This property will be sent by the client too.
According to MSDN the KnownTypeAttribute class allows you to specify, in advance, the types that should be included for consideration during deserialization. The WCF service generally accepts and returns the base type. If you expect the service to accept and return an inherited type then we use the knowntype attribute.
[KnownType]
is needed to tell it about subtypes. The disadvantage of not using it is that the following won't work:
[DataContract] class Foo {} [DataContract] class Bar : Foo {}
with a method on the WCF interface that returns:
public Foo GetFoo() { return new Bar(); }
Without the attribute, the serializer (especially for mex/proxy-generated types) won't know about Bar
, and it will fail. With the attribute:
[DataContract, KnownType(typeof(Bar))] class Foo {}
it will work. This only applies to DataContractSerializer
- with NetDataContractSerializer
you get the type data in a different way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With