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:

image

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:

image

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

Happy Coding.

Advertisements

One thought on “Generics in WCF Data Contract

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s