Return non-nullable type with C# generics, accepting a nullable type

I want a generic method which checks for null, if it’s null it should throw an exception, if not, it should return the non-nullable type of it.

I have a generic method, called GetRequiredValue:

public static TValue GetRequiredValue<TClass, TValue>(this TClass obj, Expression<Func<TClass, TValue>> expression)
{ 
    // Omitted reflection logic to get property value of the object
    var value = ...;

    if (value is null) throw new Exception("Value is null.");
    
    return value;
}

A class, containing a nullable string property:

public class MyClass
{
    public string? Name { get; set; }
}

When calling GetRequiredValue, the return type is of type string?, but I know it’s the non-nullable version:

var val = obj.GetRequiredValue(x => x.Name); // return type is string?

Is it even possible to return the non-nullable type?

>Solution :

This is where NotNullAttribute should be used.

Specifies that an output is not null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.

Annotate the return type of GetRequiredValue with it:

[return: NotNull]
public static TValue GetRequiredValue<TClass, TValue>(this TClass obj, Expression<Func<TClass, TValue>> expression)

See also: Nullable static analysis

Leave a Reply