Before reading this article, I highly recommend reading my previous parts:
- Introduction to WCF: Part 1
- Introduction to Endpoint in WCF: Part 2
- How to Make Changes to WCF Service Without Breaking Client in WCF: Part 3
- How to Make Changes to WCF Service Without Breaking Client in WCF: Part 3.
- Method overloading in WCF – Part 4.
- What a DataContract and DataMember are in WCF: Part 5.
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. In other words, by default you cannot use a subclass of the data contract class instead of its base class. We need to tell explicitly to WCF about the subclass using the knowntype attribute. Let me explain with an example.
Create a WCF application and implement the following datacontract.
- using System.Runtime.Serialization;
- using System.ServiceModel;
- namespace WcfDemo
- {
- [ServiceContract]
- public interface IBuilder
- {
- [OperationContract]
- Builder GetBuilder();
- [OperationContract]
- Builder GetBuilderById(Builder builder);
- }
- [DataContract]
- public class Builder
- {
- [DataMember]
- public int BuilderId { get; set; }
- [DataMember]
- public string BuilderName { get; set; }
- [DataMember]
- public string MobileNo { get; set; }
- public enum BuilderType { DayBasic = 1, ContractBasis = 2 }
- }
- public class DayBasic : Builder
- {
- public int LabourCharges { get; set; }
- public int WorkedDay { get; set; }
- public enum LabourType { Fitter =1, Helper =2}
- }
- public class ContractBasis : Builder
- {
- public int TotalAmount { get; set; }
- public int DayComplited { get; set; }
- }
- }

Rahul ChoudharyPosted Mar 23, 2018, 1:02 AM
Looks like Copy Paste of Kudvenkat's Blog with some changes! Here is the original link http://csharp-video-tutorials.blogspot.in/2013/11/part-7-knowntype-attribute-in-wcf_24.html
Anil Kumar MurmuPosted Jan 12, 2016, 12:31 AM
One more question do we need to specify [DataContract] attribute for DayBasic and ContractBasic class
Anil Kumar MurmuPosted Jan 12, 2016, 12:30 AM
Is my understanding clear on above article?
Anil Kumar MurmuPosted Jan 12, 2016, 12:29 AM
so what i can understand is if we are sending any derived type object to the server using WCF then during deserialization it recognizes to accept instance of derived type as well. Say instead of sending Builder object if i am sending DayBasic or ContractBasic instances.
Anupam SinghPosted Dec 6, 2014, 5:20 AM
well explained Pramod thanks for sharing.