WCF DataContract with readonly properties

Asaf R picture Asaf R · Mar 22, 2010 · Viewed 17.6k times · Source

I'm trying to return a complex type from a service method in WCF. I'm using C# and .NET 4. This complex type is meant to be invariant (the same way .net strings are). Furthermore, the service only returns it and never receives it as an argument.

If I try to define only getters on properties I get a run time error. I guess this is because no setters causes serialization to fail. Still, I think this type should be invariant.

Example:

[DataContract]
class A 
{
   [DataMember]
   int ReadOnlyProperty {get; private set;}
}

The service fails to load due to a problem with serialization.

Is there a way to make readonly properties on a WCF DataContract? Perhaps by replacing the serializer? If so, how? If not, what would you suggest for this problem?

Thanks,
Asaf

Answer

Krzysztof Kozmic picture Krzysztof Kozmic · Mar 22, 2010

put [DataMember] on backing field, you won't need a setter.