Undisposed local

CodeRush shows the Undisposed local code issue if a local variable implementing IDisposable is not disposed inside a method.

Note

CodeRush does not show the issue if the local is passed as a parameter to an external method, added to a collection, or if the current method returns the local value.

Fix

Dispose the local.

Purpose

Highlights the local variables implementing IDisposable, which are not disposed inside a method, because undisposed variables often denote an incomplete code.

Example

public void SaveItems(string[] items)
{
  if (items == null || items.Length == 0)
    return;
  StreamWriter sWriter = File.CreateText("TextData.txt");
  for (int i = 0; i < items.Length; i++)
  {
    sWriter.WriteLine(string.Format("{0} item:\r\n", i));
    sWriter.WriteLine(items[i]);
    sWriter.WriteLine();
  }
  sWriter.Close();
}

Fix:

public void SaveItems(string[] items)
{
  if (items == null || items.Length == 0)
    return;
  using (StreamWriter sWriter = File.CreateText("TextData.txt"))
  {
    for (int i = 0; i < items.Length; i++)
    {
      sWriter.WriteLine(string.Format("{0} item:\r\n", i));
      sWriter.WriteLine(items[i]);
      sWriter.WriteLine();
    }
    sWriter.Close();
  }
}