Possible null reference argument for parameter 'value' in 'bool string.Contains(string value)'

the warning is on this line on the existing

var link = Links.FirstOrDefault(linkItem => linkItem?.Contains(existing) ?? false);

the code

public void PrepareLinks()
{
    LinksAndFileNames.Clear();
    Links.Clear();

    GenerateRadarLinks();

    // Exclude links for files that already exist in the folder
    foreach (var existing in Directory.GetFiles(Folder, "*.png").Select(Path.GetFileNameWithoutExtension))
    {
        var link = Links.FirstOrDefault(linkItem => linkItem?.Contains(existing) ?? false);
        if (link != null)
        {
            Links.Remove(link);
        }
    }
}
1

There are 1 best solutions below

0
On

Path.GetFileNameWithoutExtension returns a string?. Such a value could contain a null (even though realistically it's not going to).

You could just say "ignore it" with the ! postfix operator

var link = Links.FirstOrDefault(linkItem => linkItem?.Contains(existing!) ?? false);

Or test it

if (existing == null) continue;
var link = Links.FirstOrDefault(linkItem => linkItem?.Contains(existing) ?? false);

You can however improve the efficiency of your method with two things

  • Use EnumerateFiles instead of GetFiles, as the latter returns an array.
  • Get the index of the list match and remove at that match

foreach (var existing in Directory.EnumerateFiles(Folder, "*.png").Select(Path.GetFileNameWithoutExtension))
{
    if (existing == null) continue;
    var index = Links.FindIndex(linkItem => linkItem?.Contains(existing) ?? false);
    if (index != -1)
    {
        Links.RemoveAt(index);
    }
}

If you want to remove all possible matches, you can simply do

Links.RemoveAll(linkItem => linkItem?.Contains(existing) ?? false);