Click here to Skip to main content
14,882,280 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have built an application in VS2019.  I am implementing the IDisposable interface.  It compiles and runs fine.  But when I run the Code Analyzer I get a warning:

"Warning	CA2213	'MainForm' contains field 'MainForm.myClassInstance' that is of IDisposable type: 'MyClass'. Change the Dispose method on 'MainForm' to call Dispose or Close on this field."

My code looks something like this:

public class MyClass : IDisposable
{
        public MyClass()
        {
            ... Do Some Work Here
        }

        
        ~MyClass()
        {
            Dispose(false);
        }

}

public partial class MainForm : Form
{
        MyClass myClassInstance = null;
        

        public MainForm()
        {
            InitializeComponent();
            UserInitialization();
        }
        private void UserInitialization()
        {
            myClassInstance = new myClass();
            
            myClassInstance.Dispose();

            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
 
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            myClassInstance.Dispose();   
        }
}


What I have tried:

I have set my object to null, I have called Dispose in my MainForm, I have called the Dispose method in my MainForm_FormClosingEventHandler and I have an explicit destructor in MyClass that calls the Dispose method.... I have also tried "GC.SuppressFinalize(this)" but I still get the warning. I have run the app for days and I don't see any problem but I want to make sure I don't have any memory leaks.  Any ideas appreciated.
Posted
Updated 29-Nov-19 17:25pm

1 solution

multiple solutions but there is no reason why this warning message appears.
currently Form does not allow to override Dispose() from component, movingmyClassInstance.dispose to Form.Dispose would have solved this problem but as of now either you can move this property to local to your method and suppress it.


#pragma warning disable IDE0069 // Disposable fields should be disposed
        private MyClass myClassInstance = null;
#pragma warning restore IDE0069 // Disposable fields should be disposed
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900