Search code examples
c#fxcopca2202

CA2202 Warning for ForEach loop


The fxcop analysis gives the CA2202 warning for the following method body over the foreach line:

public void LogAnalysis(IEnumerable<string> steps, bool append = false)
{
    if (steps != null)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            foreach (string step in steps) // this is line 34
            {
                sb.AppendLine(step);
            }
            if (append)
            {
                sb.Insert(0, string.Format(
                     CultureInfo.InvariantCulture, 
                    "__________Logging started at {0}__________\n",
                     DateTime.Now.ToString(CultureInfo.InvariantCulture)));

                File.AppendAllText(AnalysisLogFile, sb.ToString());
            }
            else
            {
                File.WriteAllText(AnalysisLogFile, sb.ToString());
            }
        }
        catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
        {
            LogError(e.Message);
        }
        sb.Clear();
    }
}

Warning CA2202 Object 'steps.GetEnumerator()' can be disposed more than once in method 'LoggingService.LogAnalysis(IEnumerable, bool)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 34

I have done some research and seen that nested using statements and Dispose calls cause the analyzer to freak and give this warning, but I do have neither an explicit Dispose call nor a using block. I have not encountered another case where this warning pops for the foreach loop. I know how to suppress the warning but I just wanted to understand what could be the cause of this?


Solution

  • Based on the comments of canton7, I realized that when you force the code analysis using the menu Analyze>Run Code Analysis, it forces using the old binary fxcop even if you have installed the new Roslyn Nuget Package. The new analyzers are used automatically on build, and when I have used the new ones the warning mentioned in the question have vanished.