Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use the KnownType attribute?

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?

like image 354
bwerks Avatar asked Jul 02 '10 17:07

bwerks


People also ask

What is the KnownType attribute in WCF?

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.

Which WCF attribute specifies that the data type can be used by client application?

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.


1 Answers

[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.

like image 200
Marc Gravell Avatar answered Oct 04 '22 16:10

Marc Gravell