Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading