Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1821 Remove empty Finalizers

Why VS complains about this finalizer?

VS 2017 -- 15.3.5
Microsoft Code Analysis 2017 -- 2.3.0.62003

using System;

namespace ConsoleApp
{
    class DisposableClass : IDisposable
    {
#if DEBUG
        ~DisposableClass() // CA1821 Remove empty Finalizers
        {
            System.Diagnostics.Debug.Fail("Forgot Dispose?");
        }
#endif

        public void Dispose()
        {
#if DEBUG
            GC.SuppressFinalize(this);
#endif
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
like image 518
apocalypse Avatar asked Oct 18 '17 19:10

apocalypse


1 Answers

This looks to be a bug in the Analyzer.

From the Jun 23 comment in the issue:

@nguerrera Thanks, you are right that the analyzer is reporting a valid issue on release build. However, there is still an issue in the analyzer - it shouldn't fire if the enclosing method is also conditionally excluded. For example, the following still fires the diagnostic in both release and debug builds.

#if DEBUG
    ~InvisibleEditor()
    {
        Debug.Assert(Environment.HasShutdownStarted, GetType().Name + " was leaked without Dispose being called.");
    }
#endif
like image 104
Eric Olsson Avatar answered Oct 12 '22 07:10

Eric Olsson