Generics

You cannot define WCF contracts that rely on generic type parameters. Generics are specific to .NET, and using them would violate the service-oriented nature of WCF. However, you can use bounded generic types in your data contracts, as long as you specify the type parameters in the service contract and as long as the specified type parameters have valid data contracts, as shown in Example 3-15.

Example 3-15. Using bounded generic types

[DataContract]
class MyClass<T>
{
   [DataMember]
   public T MyMember;
}

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void MyMethod(MyClass<int> obj);
}

When you import the metadata of a data contract such as the one in Example 3-15, the imported types have all type parameters replaced with specific types, and the data contract itself is renamed to this format:

<Original name>Of<Type parameter names><hash>

Using the same definitions as in Example 3-15, the imported data contract and service contract will look like this:

[DataContract]
class MyClassOfint
{
   int MyMemberField;

   [DataMember]
   public int MyMember
   {
      get
      {
         return MyMemberField;
      }
      set
      {
         MyMemberField = value;
      }
   }
}

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void MyMethod(MyClassOfint obj);
}

If, however, the service contract were to use a custom type such as SomeClass instead of int:

[DataContract]
class SomeClass
{...}

[DataContract]
class MyClass<T>
{...}

[OperationContract]
void MyMethod(MyClass<SomeClass> obj);

the exported data contract might look like this: ...

Get Programming WCF Services, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.