Search code examples
c#.netwinformsdatasetidisposable

Dispose of public dataset


I would like to declare a class Level DataSet in a Form code.

public partial class Frm_Stazione : Form
    {
        public Frm_Stazione()
        {
            InitializeComponent();
        }

    private readonly DataSet DS = new DataSet();

    private void Frm_Stazione_Load(object sender, EventArgs e)
    {
     ………
    }
  }

It is declared that way because the dataset must be accessible by different voids and must remain available until the Form is closed. My question is this: Visual Studio version 2019, indicates this error:

'IDE0069 The DS disposable field is never deleted'.

Certainly I'm wrong something, which can be my mistake. The code is written in C#.


Solution

  • For most of the components (not controls) when you drop an instance of the component on the form, the designer adds required code for disposal, but for DataSet , for some reason it doesn't add the dispose-related code.

    But to be in safe side, if you want to dispose the data set, you can follow the same pattern which is used by the framework for all other component and it's defining a components container and adding all components to the container, then in the Dispose, dispose the container. This way, you will have a much cleaner code in dispose method.

    To to so, in case the form doesn't have dispose-related code in designer.cs file, then you can easily add the following code to the form1.cs file:

    private System.ComponentModel.IContainer components = new System.ComponentModel.Container();
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
    

    It will guarantee all the components will be disposed.

    If the code exists in designer.cs just ignore above step. Then in your constructor just add the data set to the components container:

    public Form1()
    {
        InitializeComponent();
        components.Add(myDataSet);
    }