Search code examples
c#generics.net-8.0c#-12.0

Generic method that receives typed non null value and can return null value


below is some code that represents what I am trying to do:

private T? SomeMethod<T>(T prm)
{
    if (someCondition)
        return prm;

    return null;
}

So, the idea is this: a method receives a parameter that has a value (notnull), but the return value of the method can be either a value, or null.

Above code does not compile with message "Cannot convert null to type parameter 'T".. If I add constraint (where T : class, or where T : struct), then it will compile, but I cannot do that, since T can be both struct and class.

So, is this possible with C#?


Solution

  • You can use default:

    public T? SomeMethod<T>(T prm)
    {
        // ...
    
        return default;
    }
    

    But there is another gotcha which you should be aware about - for unconstrained generic parametersif T is a value type then T and T? will match, i.e. SomeMethod<int> will return int, not int? and for SomeMethod<int?> it will return int? (see this answer for more details). There is a bit dirty/hacky workaround for the problem - create 2 different methods with default parameters and constrain them to struct/class:

    public T? SomeMethod<T>(T prm, T? _ = null) where T : struct
    {
        // ...
    
        return default;
    }
    
    public T? SomeMethod<T>(T prm, T? _ = null) where T : class
    {
        // ...
    
        return default;
    }
    

    Which will work correctly for both value and reference types and will prevent/warn passing nullable counterparts (i.e. SomeMethod<int> will return int? and SomeMethod<int?> will not compile).