16

I was wondering if there was some sort of cheat sheet for which objects go well with the using statement... SQLConnection, MemoryStream, etc.

Taking it one step further, it would be great to even show the other "pieces of the puzzle", like how you should actually call connection.Close() before the closing using statement bracket.

Anything like that exist? If not, maybe we should make one.

John B
  • 20,062
  • 35
  • 120
  • 170
  • Why would you need to call connection.Close() before the end bracket? I don't know that there are many other pieces to the puzzle. – John Saunders Jun 23 '09 at 15:35
  • Why a list? You can easily check if an object implements IDisposable. – vgru Jun 23 '09 at 15:36
  • @Groo: You really have to check the docs, some types hide the Dispose(). So not that easy. – H H Jun 23 '09 at 15:39
  • @John Saunders: Are you sure you shouldn't close the SQL connection? – John B Jul 28 '09 at 18:15
  • @John Saunders: Let the people decide: http://stackoverflow.com/questions/1195829/do-i-have-to-close-a-sqlconnection-before-it-gets-disposed – John B Jul 28 '09 at 18:22

9 Answers9

14

Perhaps glance at my post on this at http://www.lancemay.com/2010/01/idisposable-cheat-sheet/. Not sure if that's what you're looking for, but based on the original question, it sounds like it may be.

Lance
  • 5,655
  • 4
  • 30
  • 32
  • 2
    Cool! This is exactly what I was originally looking for! – John B Apr 29 '10 at 13:03
  • wow so many comments, while this is the answer! thanks Lance! – aron Mar 16 '12 at 02:55
  • 2
    Link is broken! – CFreitas Nov 05 '20 at 22:49
  • Lance's post can be view via the Internet Archive [link](https://web.archive.org/web/20200519180130/http://www.lancemay.com/2010/01/idisposable-cheat-sheet/) – nwsmith Apr 22 '22 at 16:30
  • Should have posted an actual answer instead of a self-serving link to boost your own ad revenue. – Bill Tarbell Dec 16 '22 at 14:23
  • @BillTarbell, wow, guy; 12 years on and you're coming in hot. o.0 Also, even back then I had no revenue. I posted it because it was relevant, I had written it, and is still the top ranked answer to boot... – Lance Sep 01 '23 at 16:48
10

Microsoft FxCop has a rule checking that you use an IDisposbale in a using block.

Dmitry Risenberg
  • 2,321
  • 2
  • 18
  • 22
7

The following C# method will list all IDisposable types found in a certain assembly. (Used namespaces: System, System.Collections.Generic, System.IO, System.Reflection)

  static void PrintDisposableTypesFromFile(String path)
  {
     Assembly assembly = Assembly.LoadFrom(path);
     foreach (Type type in assembly.GetTypes())
        if (type.GetInterface("IDisposable") != null)
           Console.WriteLine(type.FullName);
  }

The following C# method makes use of the previous one to do the same for all assemblies in a directory and its subdirectories, e.g. "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727":

  static void PrintDisposableTypesFromDirectory(DirectoryInfo dir, bool warn)
  {
     foreach (FileInfo file in dir.GetFiles("*.dll"))
     {
        try
        {
           PrintDisposableTypesFromFile(file.FullName);
        }
        catch (Exception ex)
        {
           if (warn)
           {
              Console.Error.WriteLine(
                 String.Format(
                    "WARNING: Skipped {0}: {1}",
                    new object[] { file.FullName, ex.Message }));
           }
        }
     }
     // recurse
     foreach (DirectoryInfo subdir in dir.GetDirectories())
        PrintDisposableTypesFromDirectory(subdir, warn);

  }

I'm not sure the list of all disposables is very useful, but I've used similar code to find other interesting things like the full list of text encodings supported by the .NET framework.

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
4

If you are unsure whether a class implements IDisposable or not, enclose it in a using block regardless. If you get a compile error, just remove it. You'll only lose a few seconds typing time.

Christian Hayter
  • 30,581
  • 6
  • 72
  • 99
  • 1
    In most cases, if there is a Dispose method it will implement IDisposable. – weiqure Jun 23 '09 at 15:47
  • @weiqure - but not vice versa – H H Jun 23 '09 at 16:26
  • Always vice versa as there is no IDisposable-implementing class without a Dispose method. And I have not yet seen a class that has a Dispose method but does not implement IDisposable. – weiqure Jun 23 '09 at 20:00
3

In addition to the other answers, note that a class might implement IDisposable but not have Dispose come up in the intellisense list.

class MyClass :IDisposable
{
    void IDisposable.Dispose()
    {
        /* Stuff */
    }
}
billpg
  • 3,195
  • 3
  • 30
  • 57
3

If you are using Visual Studio you can press F12 on a type declaration it will take you to a meta-data screen or the class definition (if you have the source code). If you keybindings are different right-click and "go to definition". From there you can see what a class implements. I suggest doing this for all classes the first time you encounter them to get a "feel" for what the class can do.

Kleinux
  • 1,511
  • 10
  • 22
  • 2
    Yes but not every class that implements IDisposable implements it directly. Take DataTable for example (which, BTW, you don't need to Dispose... but that's another conversation http://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable.) – Grinn Jun 15 '10 at 14:43
2

An simple way to get a list of types that implement IDisposable is to crack open Reflector, navigate to System.IDisposable, expand the node, and then expand the 'Derived Types' node.

To be sure that your list is complete, verify that all the assemblies you're using have been 'Open'ed in Reflector.

Kevin Pullin
  • 13,122
  • 3
  • 24
  • 33
1

With ReSharper you can show all derived types. Maybe you can do it with the object browser without ReSharper, too. Go to the interface definition and look for "show inheritors".

tanascius
  • 53,078
  • 22
  • 114
  • 136
  • Nor knowing ReSharper, does it work for interfaces? And is it Project-wide or could you include the GAC and other folders? – H H Jun 23 '09 at 15:45
  • It works for everything, and can include library assemblies, including those in the GAC. You can also click in an assignment, and it will suggest a using block if the type being assigned implements IDisposable. – John Saunders Jun 23 '09 at 15:48
0

A quick&dirty way of checking if a type implements IDisposable is to create an instance of it and check if the instance has a Dispose() member function. If it does then you can be 99% sure that it implements IDisposable.

Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76