© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•5mo ago•
22 replies
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;
}
/// <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)
{
}
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
collection
is
IEnumerable<Item>
IEnumerable<Item>
(not nullable)
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Nullability in an assertion checking method [Answered]
C#CC# / help
4y ago
✅ Using Linq's Cast Method
C#CC# / help
4y ago
Getting Rid of Nullability Warnings
C#CC# / help
4y ago
✅ EFCore LINQ methods
C#CC# / help
3y ago