C
C#2y ago
malkav

✅ How to return null in a generalized method?

So I've got this general method that is being used in a lot of functions that I'm using to return a database call through API calls, and I've got this method for it:
public static async Task<T?> ResultResponse<T>(this HttpResponseMessage result, string message)
{
if (!result.IsSuccessStatusCode) return null;
string responseBody = await result.Content.ReadAsStringAsync();
return responseBody
.Contains(message,
StringComparison.CurrentCultureIgnoreCase)
? null
: JsonConvert.DeserializeObject<T>(responseBody);
}
public static async Task<T?> ResultResponse<T>(this HttpResponseMessage result, string message)
{
if (!result.IsSuccessStatusCode) return null;
string responseBody = await result.Content.ReadAsStringAsync();
return responseBody
.Contains(message,
StringComparison.CurrentCultureIgnoreCase)
? null
: JsonConvert.DeserializeObject<T>(responseBody);
}
However I apparently can't return null on this type T? is there any way I can still return null here? Should I make Task<object> instead?
2 Replies
malkav
malkav2y ago
So any class (data model) I pass in T will then be returned as a new instance of that class? Because the idea is for it to return a null instead of that class 😅 there are however, I think 5 or 6 different classes I could pass in there. ah okay I was trying to build constraints though, but I'd have to make a where T : x OR y OR z ... thing I tried this: where T : ICollection<Assignment>, ICollection<MonthlyHours>, ICollection<Invoice>, ICollection<CUser>, BaseModel, Assignment, MonthlyHours, Invoice, CUser but obviously that'll break 😅
Accord
Accord2y ago
Closed!