Tpcool
Tpcool

Reputation: 59

Assign Different Type to Class Property

I have created a class to store data from API calls I am making. It returns JSON with some meta information, and then an array of data depending on the call being made. The meta information will always have the same fields, so I have created a "Root" class for this, but the data will be different depending on the call being made, so I have created different classes for each type of data, e.g. user data, company data, etc. As shown below, I currently have the "data" property set to a list of objects, but I am trying to figure out the best way to incorporate the different types of data that can be returned, since it will vary based on the call being made.

Root class object

Right now I have the data saved as a list of objects, but I would like this to change depending on what data I am receiving. Like, if I am retrieving users, I would like for it to be a list of users.

What is the ideal way to accommodate for this? The only way I can think to do it now is to create a different "Root" class for every type of data I am expecting to receive, but that doesn't feel like it should be the most concise way to do it. I was looking into making this a factory design pattern but I wasn't sure that it fit this scenario.

Upvotes: 0

Views: 1022

Answers (1)

Martin
Martin

Reputation: 3286

Just use a generic base class:

public abstract class ApiCallResult<T>
{
    // With your properties
    // public int Limit { get; set; }
    // [...]
    //
    public IEnumerable<T> Data { get; set; }
}

Then define a result per api call.

public class UserApiCallResult : ApiCallResult<User>
{
}

Created a small working example here: dotnet fiddle

Upvotes: 1

Related Questions