Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net method with generic parameter

I have a generic APIResponse<T> object that wraps the result of an API call:

public class APIError
{
    public string ErrorMessage { get; set; }
}

public class APIResponse<T>
{
    public T Result { get; set; }
    public APIError Error { get; set; }
    public bool HasError
    {
        get { return Error != null; }
    }
}

I have a method that calls an API:

public APIResponse<string> GetUserName()
{
    APIResponse<string> response = new APIResponse<string>();

    try
    {
        // make http request
        response.Result = httpResponse;
    }
    catch
    {
        response.Error = new APIError { ErrorMessage = "Some error occurred" };
    }

    return response;
}

// I call the method like this
APIResponse<string> userNameResponse = GetUserName();

// i need to handle the apiResponse
HandleAPIResponse(userNameResponse);

I want to create a generic method that inspects the APIResponse<T> object, and throws an exception if it has an error, but i can't make it work without specifying the result type:

public void HandleAPIResponse(APIResponse<T> apiResponse)
{
    if (apiResponse.HasError)
        throw new Exception(apiResponse.Error.ErrorMessage);
}

Can i make a method that accepts APIResponse<T> as parameter, but without specifying the type of T?

like image 537
Catalin Avatar asked Aug 05 '26 10:08

Catalin


1 Answers

The method definition should be as follows:

public void HandleAPIResponse<T>(APIResponse<T> apiResponse)
{
    if (apiResponse.HasError)
        throw new Exception(apiResponse.Error.ErrorMessage);
}
like image 176
twoflower Avatar answered Aug 07 '26 01:08

twoflower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!