In my WCF training, I often get questions that can we expose a generic type as DataContract in WCF? Yes, WCF allows us to expose the generic types as Data Contract.
Let us say we have a generic type Foo. We can apply data contract on the Foo as follows:
[DataContract] public class Foo<T> { [DataMember] public T fooName { get; set; } [DataMember] public T fooAge { get; set; } }
We can use Foo<T> generic type in operation contract as follows:
[OperationContract] Foo<string> GetFoo();
The service is implemented as follows:
public Foo<string> GetFoo() { Foo<string> foo = new Foo<string>(); foo.fooAge = "32"; foo.fooName = "dj"; return foo; }
This is how you can create a service using generic types as Data Contract. However at the client side generic type will be not shown and data contract will be exposed with the name appended by type. So at the client side you will have FooOfString class as shown below:
We can consume the service created above as follows:
Service1Client proxy = new Service1Client(); FooOfstring foo = proxy.GetFoo(); Console.WriteLine(foo.fooAge + foo.fooName); Console.ReadKey(true);
You will get expected output as shown below:
We learnt that the WCF supports exposing a generic type as DataContract.
Happy Coding.
Leave a Reply