© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
6 replies
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?
T?
is there any way I can still return null here? Should I make Task<object> instead?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Generalized Storage
C#CC# / help
6mo ago
❔ Return in the middle of a method
C#CC# / help
3y ago
Method doesnt return
C#CC# / help
3y ago
Cannot return null from an action method with a return type of 'Microsoft.AspNetCore.Mvc.JsonResult'
C#CC# / help
11mo ago