c# REST API polymorphic return type

Viewed 1706

I have created data contracts as below having inheritance:-

[DataContract(Name = "Animal")]
public class Animal { ... }

[DataContract(Name = "Dog ")]
public class Dog : Animal { // Has some Dog specific member properties }

[DataContract(Name = "Cat ")]
public class Cat : Animal { // Has some Cat specific member properties }

And I'm using ASP.NET WebApi to provide a REST API like:

[HttpGet]
public Task<Animal> Get(string type) 
{ 
    switch(type)
    {
        case "dog":
            Dog dog = GetDogDetails();
            return Task.FromResult(dog);
            break;

        case "cat":
            Cat cat = GetCatDetails();
            return Task.FromResult(cat);
            break:
    }
}

I am not able to return the respective animal types. I get the following error:- "Cannot implicitly convert Dog to Animal".

Also is this polymorphic response a good thing as per REST API standards.

1 Answers
Related