Search code examples
c#wcfstructvalue-type

Using Structs with WCF Services


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 and find myself inspired to ask to see if my annoyance is warranted.

I've in past always used classes - probably in part because that's what samples always show but as I think about it now, for other "intuitive" reasons:

  • I started contract style by defining a separate project with interfaces representing the types that would be passed back and forth by the service.

  • I use LINQ a lot, so tests for nullability are implicit with reference types whereas with structs and other value types I'd always need to mark nullable.

Those are some that come to me right away although I'll admit it's more intuitive than a bulleted list in my mind. I thought to ask the question because I'm dealing with a service that returns structs and having to write when dealing with return values:

var foo = Bar.Value.MyField;

instead of

var foo = Bar.Value;

Solution

  • 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).