Tuesday, October 26, 2004

VJs Tip Of The Day - October 26th 2004

Converting Collection to Array

Some days back we talked about the way we create a strongly typed collection (Check Oct 14th 2004 Tip)... Now say this collection is returned somewhere and the consumer does not need the collection but needs array of the objects inside the collection...
To make it more clear... Say you have a object "X" and its collection is called "CollectionX"... Now there is a method which is defined in a following way...

public CollectionX GetAllXObjects()


The consumer of this method realizes that he does not want the collection but just something like

public X() GetAllXObjects()

What can be most simply do... Write a method inside the CollectionX class and return back this.InnerList.ToArray(typeOf(X))

The reason for mentioning this is that Innerlist is a protected property and so the consumer will not be able to access it unless he inherits your collection and then tries to access it...

When is it that you are likely to face above situation...? Is is when you are working with webservices and any strongly typed collection on the server side is converted into array of the type inside the WSDL... :-)


PS: Ackg: This came up with my discussion with a colleague Matt...

No comments: