Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading