ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

WhereNotNull

I’m a big fan of the Nullable Reference Types feature added in C# 8.0. It lets the compiler catch a bunch of potential runtime errors, and I guarantee if you turn it on you’ll get a bunch of warnings. As of .NET 5.0, the entire BCL is now covered with nullable annotations, and a lot of the extended ecosystem supports them too. But there are situations where the compiler is unable to work out that you’ve done a null check, meaning you either have to use the “null-forgiving operator” (where you append a bang to the identifier, like item!.Name), disable the null checking, or just ignore the warning. The WhereNotNull extension method filters out nulls and changes the expression type accordingly. source: https://rendle.dev/posts/where-not-null/

Source

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class
{
    foreach (var item in source)
    {
        if (item is not null) yield return item;
    }
}

Example

IEnumerable<string?> files = project.MetadataReferences
.OfType<PortableExecutableReference>
.Select(p => p.FilePath)
.Where(f => f is not null);

// Versus

IEnumerable<string> files = project.MetadataReferences
.OfType<PortableExecutableReference>
.Select(p => p.FilePath)
.WhereNotNull();

Author: Mark Rendle

Submitted on: 5 dec. 2020

Language: csharp

Type: ienumerable-t

Views: 4574