Generics in WCF Data Contract

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:


    public class Foo<T>
        public T fooName { get; set; }
        public T fooAge { get; set; }

We can use Foo<T> generic type in operation contract as follows:

        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);

You will get expected output as shown below:


We learnt that the WCF supports exposing a generic type as DataContract.

Happy Coding.

One response to “Generics in WCF Data Contract”

  1. […] Generics in WCF Data Contract (Dhananjay Kumar) […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at