Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF CollectionDataContract

I recently noticed in one of the articles the wcf service operation returned a collectiondatacontract

Users GetUsers(string someInput);

And Users type was defined as below:

[CollectionDataContract]
    public class Users : List<User>
    {
        public Users()
        {
        }

        public Users(IEnumerable<User> users) : base(users)
        {
        }
    }

Does returning a collectiondatacontract (like Users in this case) serve a different purpose than simply returning List<User> ?

like image 818
stackoverflowuser Avatar asked Apr 21 '11 00:04

stackoverflowuser


2 Answers

As far as I understand, this attribute will give you some control over what names the elements will have in the final xml string, after the DataContractSerializer has done its work serializing your collection.

This can be useful when you have to parse the result later manualy( in other words you will know what element to look for in that xml text, to find your collection and its parts).

Take a look at this for examples and more info:

http://msdn.microsoft.com/en-us/library/aa347850.aspx

like image 59
Andrei Avatar answered Oct 07 '22 06:10

Andrei


if you return a List, the data serializer has a specific way of generating xml. I dont know how it does it for List, but if it was an array it would have generated something like -

<arrayOfUsers>
<User>
...here User object 1
</User>
...etc.
</arrayOfUsers>

But using CollectionDataContract you can serialize it and better expose it for consumers who may be creating XML by hand. Example - I would be able to give - CollectionDataCOntract(Name="AllUsers") // i dont remember ItemName or Name

then the XML expected would be something similar to -

<AllUsers>
<User>
...here User object 1
</User>
...etc.
</AllUsers>

Thats one utility for this.

like image 45
Sachin Nayak Avatar answered Oct 07 '22 06:10

Sachin Nayak