C#C
C#4mo ago
TheBoxyBear

Confusion with nullability of a custom LINQ method

I have this custom extension method I used a lot in my project, however every time I use it, it trips nullability checks and thinks I'm using a possibly null value.
/// <summary>    
/// Tries to get the first item that meets a condition from a collection.
/// </summary>
/// <typeparam name="T">Type of items in the collection</typeparam>
/// <param name="source">Collection to get the first item of</param>
/// <param name="predicate">Method that returns <see langword="true"/> if a given item meets the condition</param>
/// <param name="item">Found item</param>
/// <returns><see langword="true"/> if an item was found</returns>
public static bool TryGetFirst<T>(this IEnumerable<T> source, Predicate<T> predicate, [MaybeNullWhen(false)] out T item)
{
    ArgumentNullException.ThrowIfNull(predicate);

    foreach (T t in source)
        if (predicate(t))
        {
            item = t;
            return true;
        }

     item = default;
     return false;
}
Example usage causing the false positive
if (collection.TryGetFirst(item => item.IsActive, out Item item)
{
}
Here, the warning comes at the out parameter. If I make the out in the usage nullable, then the generic type takes the nullabiltiy and the warning moves to when I use the item inside the if. collection is IEnumerable<Item> (not nullable)
Was this page helpful?