CRK
CRK

Reputation: 607

dispose resource in C#

ProgressBar pBar = new ProgressBar(obj);

if(_FileRead!=false)
{
    pBar.Text = langSupport.GetMessages("123", cultureName);
    pBar.ShowDialog();
}

In this example how I can dispose "pBar" resource. Below I have specifide 3 ways, which is the best way of object dispose?

  1. pBar.Dispose();
  2. pBar = null;
  3. pBar.Dispose(); pBar = null;

Upvotes: 1

Views: 117

Answers (2)

Oded
Oded

Reputation: 498924

Wrap the creation of the ProgressBar in a using statement.

using(ProgressBar pBar = new ProgressBar(obj))
{
   if(_FileRead!=false)
   {
       pBar.Text = langSupport.GetMessages("123", cultureName);
       pBar.ShowDialog();
   }
}

Since it implements IDisposable, this is the best way to ensure proper disposal.

Upvotes: 6

Steve
Steve

Reputation: 50573

If it supports it I would use:

using(ProgressBar pBar = new ProgressBar(obj))
{
  if(_FileRead!=false)
  {
      pBar.Text = langSupport.GetMessages("123", cultureName);
      pBar.ShowDialog();
  }
}

In that way when it exits the using it disposes of all the relevant objects.

Upvotes: 2

Related Questions