0

I just enabled FxCop Code Analyzers and, while fixing warnings this one could not be fixed:

CA1062: Validate arguments of public methods

        public static string SanitizeFileName(this string fileName)
        {
            if (fileName is null) throw new ArgumentNullException(nameof(fileName));

            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(c, '_');
            }

            return fileName;
        }

Compiller still throwing warning CA1062 accessing fileName

Thanks in advance

Arthur JF
  • 81
  • 5
  • Does it work if you change `is null` to `== null`? (https://developercommunity.visualstudio.com/content/problem/676210/ca1016-does-not-recognize-checking-null-with-is.html) – mjwills Jul 22 '20 at 01:27
  • Yep. That did the trick. Is there an explanation? Thanks! – Arthur JF Jul 22 '20 at 01:38
  • Did you read the comments at https://developercommunity.visualstudio.com/content/problem/676210/ca1016-does-not-recognize-checking-null-with-is.html ? – mjwills Jul 22 '20 at 02:02

1 Answers1

0

The CA1062 warning is a design warning (CA1062: Validate arguments of public methods), an externally visible method dereferences one of its reference arguments without verifying whether that argument is null, it will show this warning.

I have reproduced the problem on my side using your code, it seems that this issue is related to the is operator, after changing the is operator to "==", the warning disappears.

    public static string SanitizeFileName(this string fileName)
    {
        if (fileName == null) throw new ArgumentNullException(nameof(fileName));

        foreach (char c in System.IO.Path.GetInvalidFileNameChars())
        {
            fileName = fileName.Replace(c, '_');
        }

        return fileName;
    }

Besides, according to the sample code in the CA1062 warning, if you want to check whether the string is null, you could use the following code:

    public void Validate(string input)
    {
        if (input == null)
        {
            throw new ArgumentNullException(nameof(input));
        }
        if (input.Length != 0)
        {
            Console.WriteLine(input);
        }
    }
Zhi Lv
  • 18,845
  • 1
  • 19
  • 30