❔ How to cast to a generic of object?

I am using an external api that returns dynamic data. It could be a string, a list or a table.

In my code, I am building a controller endpoint that will read the data from this API, parse the data from the body, and return as a result to the requester.

To help me with that, I have attempted to build a generic ApiResult<T> that will contain the parsed data. The issue is that I am attempting to cast the ApiResult<T> to an ApiResult<object> and unfortunately it doesn't allow me to do that since object and T doesn't seem to be compatible.

Could anyone help me? I don't need the result to be strongly typed, but I really wanted to have the Parse methods strongly typed to have intellisense.

public class ApiResult<T> where T : class
{
    public bool Success { get; set; }
    public T Data { get; set; }
}

public class ApiResult : ApiResult<object>
{
}

public static class HttpResponseExtensions
{
    public static ApiResult ParseApiResult(this HttpResponse response)
    {
        // I cannot do this because ApiResult<object> is not compatible with ApiResult<T>
        return response.Headers["Structure"] switch
        {
            "text" => response.ParseString(),
            "list" => response.ParseList(),
            "table" => response.ParseTable(),
            _ => null
        };
    }

    private static ApiResult<List<string>> ParseList(this HttpResponse response)
    {
        return new ApiResult<List<string>>();
    }

    private static ApiResult<string> ParseString(this HttpResponse response)
    {
        return new ApiResult<string>();
    }

    private static ApiResult<List<List<string>>> ParseTable(this HttpResponse response)
    {
        return new ApiResult<List<List<string>>>();
    }
}
Was this page helpful?