Home > Net >  C# Dereference of a possibly null reference
C# Dereference of a possibly null reference

Time:05-10

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?

CodePudding user response:

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);
  • Related