I am developing a WCF service designed to be consumed by non .NET clients, which performs a charge operation. I would like to be able to return either a base class DataContract or an inherited class DataContract depending on the use case.
So I have:
[DataContract]
public class ChargeResponse
{
[DataMember]
public string ID
[DataMember]
public string Description
}
For successful operations, I would like to return an inherited type having an extra DataMember such as:
[DataContract]
public class SuccessfulChargeResponse : ChargeResponse
{
[DataMember]
public string TransactionID
}
For all other cases I would return the bass class. Is this possible? Or should I just have the DataMember is the base class and return an empty value.
You are being overly complicated – you simply need to return a
ChargeResponsethat contains aTransactionID. If the operation was successfulTransactionIDwill have a value, if it wasn’t thenTransactionIDwill be null. You can extend your class a little further to contain a flag or enumeration indicating the success, and whatever properties you need to indicate what the error was.This is known as the request/response pattern and is quite common. Some (possibly very unexciting and not necessarily very new) links describing this: