Short version, you can't do what you're suggesting as you've laid it out.
Long(er) version Part A:
A web service can be considered like a class' method, and actually is a method off of your web service class. I would recommend going over some web service tutorials in order to get a better grasp of the mechanics behind setting up a web service. MSDN has a number of Microsoft stack specific tutorials that are easily found with your favorite search engine.
The return object off of a method is not allowed to have polymorphic behavior, which is essentially what your asking for.
This pseudo code is equivalent to what you're trying to create and that's why the compiler isn't allowing it. It doesn't know which DoSomething()
you're attempting to call.
class myFoo
{
public SuccessResponse DoSomething() {....}
public ErrorResponse DoSomething() {....}
}
Alternatively, you could envisage something like this:
public [SuccessResponse | ErrorResponse] DoSomething()
but that fails for what should be obvious reasons as well. C# simply doesn't support polymorphic returns.
Part B
Even if we focus on just resp.Data
, that object still has to be declared as some sort of type.
class Response
{
public Collection<someType> Data;
}
If your SuccessData
and ErrorData
implement the same interface then someType
could simply be IyourInterface
but that raises another issue. Namely, how will the end user know whether they were given good data in Data
or whether there is an error response tucked in there instead.
WCF, I believe, will be nice enough to serialize IyourInterface
for you so long as you declare it as a public part of the WCF service object. But that still doesn't resolve how your end user will know what to do.
If you're willing for a little less elegance in the response, a classic pattern is to simply bundle your success data and error objects together into another response class like this:
class myResponse
{
public SuccessResponse myRespData;
public ErrorResponse myError
}
Now, the end user checks to see if there's an error if they care. Presuming no error, then they go and look into the response data.
Based upon your comment, yes, you can do the following too:
class Response
{
public List<IYourData> Data;
public YourEnum ReturnType;
}
public class ResponseData : IYourData { ... }
public class ErrorData : IYourData { ... }
And then on the client, you can perform a simple check like this:
if( ReturnType == YourEnum.Success ) { ... }
else if( ReturnType == YourEnum.Error ) { ... }
else ...
WCF will handle the serialization of List
for you. It'll either convert to an array or pass the collection directly depending upon what settings you have in place. There are some SO Q&A's that handle that particular aspect.