The answers suggesting that you can't use an anonymous type over WCF are wrong.
If you are using the default DataContractSerializer
to serialize your types on the channel, then yes, the answers are correct. This is because the DataContractSerializer
supports the following scenarios:
- Types serialized using the
Serializable
attribute
- Types serialized using XML Serialization
- Types serialized using the
DataContract
attribute
- Plain-Old-C#-Object (POCO) Serialization
Respectively, they fail with anonymous types because of the following:
- You can't apply attributes to anonymous types.
- XML Serialization requires a default parameterless constructor, which anonymous types do not have.
- Same as 1.
- Same as 2.
However, you are not forced to use the DataContractSerializer
to serialize your messages in WCF. You can create a custom message formatter which you can use to perform the serialization yourself.
You have a problem if the types you are sending out as the results of requests are anonymous types. When you get the results back, it's going to have a definite name within a namespace (not in a .NET sense, but in a SOA sense) and you are going to have to handle the mapping of that concrete type back to the anonymous type. However, because you don't have access to the actual anonymous type or ways of constructing it in code (at least in a dynamic way), you have no choice but to pass it along as an object if it's passed back to you, which makes it kind of worthless, since everyone will have to use bad practices such as dynamic (not a bad practice in itself, but to get around these limitations in this case, yes), or cast-by-example.
So in the end I will say that while it certainly is possible to serialize anonymous types and send them over the wire, the work invovled is usually not worth it.