Search code examples
.netasp.net-coreca1062

Why compiller stills trhowing CA1062 once I validated public nullable parameter?


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


Solution

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