#673 – Types Used in using Statement Must Implement IDisposable

The using statement is a shortcut for a try/finally block where the Dispose method is automatically called on any objects instantiated as part of the using statement.

            using (StreamWriter sw = new StreamWriter(@"D:\Hi.txt"))
            {
                sw.Write("Hi !");
            }
            // StreamWriter.Dispose automatically called

Because the Dispose method is called automatically on all objects instantiated as part of the using statement, each object must belong to a type that implements IDisposable.  The example below leads to a compile-time error because Dog does not implement IDisposable and therefore does not have a Dispose method.

            using (Dog d = new Dog("Kirby", 15))
            {
                d.Bark();
            }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment