Using Linq’s Where/Select to filter out null and convert the type to non-nullable cannot be made into an extension method

You have to update your extension method to the following

public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> enumerable) where T : class
{
    return enumerable.Where(e => e != null).Select(e => e!);
}

The point here is that you are converting the IEnumerable of nullable references to not nullable ones, therefore you’ll have to use IEnumerable<T?>. where T : class generic constraint is needed to help the compiler distinguish between nullable reference type and Nullable<T> struct, as you can read here

Because of this issue between the concrete representations of nullable
reference types and nullable value types, any use of T? must also
require you to constrain the T to be either class or struct.

After that the following lines will be compiled without any warnings

var list = new List<MyObject?>();
IEnumerable<MyObject> notNull = list.NotNull();

Leave a Comment