Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dereference of a possibly null reference

I'm somewhat confused by the warning I'm getting. Here is the relevant code:

#nullable enable
public partial class FileTable<TItem> : ComponentBase, IDisposable
{
    // bunch of class code

    public async Task FilterColumn(Func<TItem, IComparable>? itemProperty, string? searchString)
    {
        ArgumentNullException.ThrowIfNull(ViewItems);

        if (itemProperty == null)
            return;

        if (searchString == null)
            searchString = string.Empty;

        await Task.Run(() =>
        {
            foreach (var item in ViewItems)
            {
                var property = itemProperty(item.Item);

                if (property == null)
                    continue;

                item.IsVisible = property.ToString().ToLower().Contains(searchString.ToLower());
            }
        });
        StateHasChanged();
    } 
}

I'm getting the warning for property.ToString() As you can see I have already added a bunch of null-checks, but none seems to get rid of the warning. As far as I can see it is impossible for property to be null at the this point. Obviously I'm missing something...so what could be triggering this warning?

like image 969
Roland Deschain Avatar asked Feb 02 '26 21:02

Roland Deschain


1 Answers

The problem is that ToString() can return null; it is bad practice, but: it can:

namespace System
{
    public class Object
    {
        // ...
        public virtual string? ToString();
        // ...
    }
}

the error goes away if you rule that out:

var s = property.ToString() ?? "";
item.IsVisible = s.ToLower().Contains(searchString.ToLower());

Note also that it is more efficient to use a comparison that ignores case, rather than forcing additional string allocations:

item.IsVisible = s.Contains(searchString, StringComparison.CurrentCultureIgnoreCase);
like image 103
Marc Gravell Avatar answered Feb 04 '26 09:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!