Per Erik Strandberg /cv /kurser /blog

To convince myself of the function of the using function of IDisposable I wrote an incredibly simple test of it.

First a simple class that implements IDisposable. As you can see it only has a constructor that sets the name of the instance and the dispose method.

using System;

namespace using_test
{
    class myDisposable : IDisposable
    {
        string m_name;
        
        public myDisposable(string name)
        {
            m_name = name;
        }
        
        public void Dispose()
        {           
            Console.WriteLine("{0} is being disposed", m_name);
        }
    }

And below in the same source file I wrote the program class with a main and two test methods. The first one returns while the idisposable is still in scope. And the second one after leaving the using curly brace.

    class Program
    {
        public static void dTest1()
        {
            Console.WriteLine("dTest1 >> started.");
            using(myDisposable foo = new myDisposable("Adam"))
            {
                Console.WriteLine("dTest1 >> return.");
                return;   
            }           
            Console.WriteLine("dTest1 >> you can not read this.");
        }
        
        public static void dTest2()
        {
            Console.WriteLine("dTest2 >> started.");
            using(myDisposable foo = new myDisposable("Bertil"))
            {
                Console.WriteLine("dTest2 >> in using statement.");
            }           
            
            Console.WriteLine("dTest2 >> done using.");
            return;   
            Console.WriteLine("dTest2 >> you can not read this.");
        }
        
        public static void Main(string[] args)
        {
            Console.WriteLine("Main >> Starting dTest1!");            
            dTest1();
            Console.WriteLine("Main >> Starting dTest2!");
            dTest2();
            Console.WriteLine("Main >> Done testing!");
            Console.WriteLine();
            
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

As we could expect the disposable is disposed of in both cases.

Main >> Starting dTest1!
dTest1 >> started.
dTest1 >> return.
Adam is being disposed
Main >> Starting dTest2!
dTest2 >> started.
dTest2 >> in using statement.
Bertil is being disposed
dTest2 >> done using.
Main >> Done testing!

Press any key to continue . . .

For reference I also added a test method that does not dispose the myDisposable:


        public static void dTest3()
        {
            Console.WriteLine("dTest3 >> started.");
            myDisposable foo = new myDisposable("Caesar");         
            Console.WriteLine("dTest3 >> done testing.");
            return;   
        }

As we could expect this test does not dispose of the instance.

Download the source code here: [1]


This page belongs in Kategori Programmering