Is there any official recommendation on using structs as return types with WCF services?
I\'m currently interacting with a service I did not write
If you can create a struct and put a [DataContract]
attribute on it - go ahead and use it! To WCF, that doesn't make a difference - WCF only requires that the class or struct in use by marked with a DataContract attribute and all the fields to be included in the serialized message are to be marked with a [DataMember]
attribute.
If you check the MSDN docs on the DataContractAttribute, it shows that you can use it on a struct as well:
[AttributeUsageAttribute(AttributeTargets.Class|
AttributeTargets.Struct|AttributeTargets.Enum,
Inherited = false, AllowMultiple = false)]
public sealed class DataContractAttribute : Attribute
UPDATE: as for when to use a struct instead of a class (in general, in .NET), see this SO question here:
When should I use a struct instead of a class?
However, since WCF is really about message passing (i.e. your client makes a method call, that call and its parameters get converted into a serialized message that gets sent across the wire and then re-assembled on the other end and turned back into a method call), I don't see any compelling reason to ever use a struct
.
All the benefits of general .NET don't really apply in the SOA-world of WCF, I would say (you're not passing around class or struct instances - see above).