Search code examples
c#web-serviceswcfservicedatamember

Generic argument property causes error on WebService


Service:

enter image description here Error:

The error is with a type that has ChainedListNode<T>. Thing is, when I remove the DataMemberAttribute from Value, the service works.

[DataContract]
public class ChainedListNode<T>
{
    [DataMember]
    public T Value { get; set; }
}

Any ideas to what's causing it and/or how to solve it?


Solution

  • The problem is that the type parameter in the open type ChainedListNode<T> means that ChainedListNode<T>.Value could contain anything at all. WCF can't create a contract which describes all the possible values which could be placed in the Value property, so it rejects the whole type. When there is no Value property, the type parameter T is irrelevant and is ignored, and everything works OK.

    In similar situations I've created a closed type derived from my generic type and used that type as my data contract:

    [DataContract]
    public class ChainedListNodeOfString : ChainedListNode<string>
    {
        [DataMember]
        public string Value { get; set; }
    }
    

    If you need to, you can create a derived type (and a related OperationContract) for each different kind of value you need to return. This makes your API more verbose, but it works.