V
V
Victor P.2021-02-26 11:59:19
Algorithms
Victor P., 2021-02-26 11:59:19

How to return string from c# generic?

Good afternoon,
I wrote a wrapper class for http calls with a dynamic type:

public async Task<T> PostPandaSpecified<T>(string pandaParams, string method)
{
            // вырезал http вызов
                var content = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    if (typeof(T) == typeof(string))
                    {
                        return content; // ошибка
                    }
                    else
                    {
                        var res = JsonConvert.DeserializeObject<T>(content);
                        return res;
                    }
                }

                throw new HttpRequestException(content);
            
}


Accordingly, if I call this method and pass any class to the return type, then this class is substituted into json deserialization and everything works out
var res = await PostPandaSpecified<SomeResultClass>(dataToSend, "url");

But if I don’t get json in response, but a simple string, I shouldn’t pass it to the json serializer, it breaks because of this, I just need to return the content.
var res = await PostPandaSpecified<string>(dataToSend, "url");

// Ошибка в этом блоке
if (typeof(T) == typeof(string))
{
    return content; // Cannot implicity convert type 'string' to 'T'
}

(explicit conversions also don't work)

How to write here correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor P., 2021-02-26
@Jeer

What a fine fellow I am, google faster than I wrote the question:

if (typeof(T) == typeof(string))
{
    return (T)(object)content;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question