Possible Duplicate:
C# WCF: When is it appropriate to use the KnownType attribute?
Not long ago, we needed in class to create, as part of a project, a C# web client. The teacher instructed us to put the attribute DataContract above each class that will be passed.
Then the teacher told us that if you have some thing like this:
A
/ \
/ \
B C
you need to write class A in the following way:
[DataContract]
[KnownType(typeof(B))]
[KnownType(typeof(C))]
public class A
{
}
Isn’t this completly against the idea of polymorphism? why should a class know who inherits the class?
This doesn’t really have anything to do with C# and polymorphism; rather with serialization. The WCF infrastructure needs to be able to take something like a byte array off the wire and create an object out of it. If class
Ais anabstracttype, there is no way that object can be instantiated. The framework needs to know what types it might receive over the wire so it can inspect the metadata and instantiate the right type of object.Put another way, the attributes don’t tell the class anything about its inheritors (indeed, the list need not include all inheritors); this is strictly so the framework will know what types it can expect to be asked to construct.
I would add, though, that adding the
DataContractandDataMemberattributes is not always required. They are available for scenarios where you may want to have more fine grained control, such as excluding a public property from serialization. Usually if the type is serializable it can be passed without the attributes.