tags:

views:

54

answers:

3

How do I return a collection of objects from a webmethod? And can this collection of objects be of different types - say of these 3 classes,

private class ClassA 
{
  int A1;
  int A2;
}

private class ClassB
{
  int B1;
}

private class ClassC
{
  int C1;
}

ClassA objA = new ClassA(...);
ClassB objB = new ClassB(...);
ClassC objC = new ClassC(...);

How can I return the objects, objA, objB and objC from a method?

+2  A: 

As different possible results from the same method? That would be ugly, and doesn't allow a rigid schema (think: WSDL) to exist. Perhaps encapsulate all 4 options on a single type that you do return? Or use some kind of inheritance and [XmlInclude]. In the case of multiple values, you can return List<TheBaseType>.

If you mean "I want all these in one hit to the method", then just wrap them:

public class MyReturnType {
    public ClassA A { get;set; }
    public ClassB B { get;set; }
    public ClassC C { get;set; }
}

and return an instance of MyReturnType (or List<MyReturnType> for multiple values).

Marc Gravell
But public class MyReturnType can either have just one or more class depending on some internal logic. That's the reason why I was thinking more in the List<varied objects> (if anything like that is possible at all?)
Narmatha Balasundaram
@Narmatha, that's possible. If each of your classes inherits from a common base, you can return `List<Base>` or `Base[]`. Absent that, you would have to return it as a list or array of `object`.
Anthony Pegram
Returning a composite MyReturnType would be the best solution in ideal cases. But the elements of this class are known only at runtime and declaring a class at run-time is difficult (not impossible). So for my needs sticking to an array of objects makes sense.
Narmatha Balasundaram
A: 

Return them as an array or list. I don't have an IDE in front of me, but it should be like

[WebMethod]
public object[] GetObjects()
{
   ...
   return new object[] { objA, objB, objC };
}

Even better if they inherit from the same base class or interface.

Anthony Pegram
A: 

You can do one of the following:

  • Have a custom object which contains all these 3 objects (not as a list, but as seperate objects) and pass this compound object.

  • If these (all three objects) are inherited from a base class then just pass a list of this base class with all these stored in the list

Mahesh Velaga