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 ofT?
must also
require you to constrain theT
to be eitherclass
orstruct
.
After that the following lines will be compiled without any warnings
var list = new List<MyObject?>();
IEnumerable<MyObject> notNull = list.NotNull();