Click here to Skip to main content
14,880,638 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I downloaded a sample dot net basics program on 'finalizers'. I have a small (probably silly) question about that. Here is the code:

C#
using System;
using System.IO;

1. namespace Finalizers
2. {
3.     internal class FileGenerator : IDisposable
4.     {
5.         public FileGenerator()
6.         {
7.         }
8.         ~FileGenerator()
9.         {
10.             // Just a debug output
11.             Console.WriteLine("Closing file!");
12.        }
13.        public void Generate(int Length)
14.        {
15.            // Here some work is done...
16.        }
17.        public void Dispose()
18.        {
19.            // Just a debug output
20.            Console.WriteLine("Disposing object!");
21.        }
22.    }
23.
24.    class Program
25.    {
26.        static void Generate()
27.        {
28.            // Here it would be better to use the C# "using" keyword instead of implicitly calling Dispose!
29.            using (var fGen = new FileGenerator())
30.            {
31.                fGen.Generate(512);
32.                //fGen.Dispose();
33.            }
34.        }
35.        static void Main(string[] args)
36.        {
37.            Generate();
38.            // Here we do some work; simulated by ReadLine statement
39.            Console.Write("Please Press Enter...");
40.            Console.ReadLine();
41.        }
42.    }
43. }


When I comment line number 32 and execute the code, still the Dispose() method of class 'FileGenerator' is being executed, of course to dispose off the object.

But when I un-comment line number 32 and execute, the method is being executed twice. once when line number 32 is encountered and next when the object is being disposed off.

Is this the way it has to be? As in, the 'Dispose()' method is already called right? Why does the compiler have to call the method again?

Thanks a lot for your help.
Posted

1 solution

When you use using statement, it means that the variable is automatically disposed at the end of the block.

So if you call the Dispose() method by yourself, it is executed twice.

You don't need to explicitly call Dispose() method in a using block.
   
Comments
Amogh Natu 15-Apr-13 6:01am
   
Oh ok. Got it. Because the call to the Dispose() method is inside the using block, the compiler calls it the second time when the end of using block is encountered. Right? Thanks a lot.
phil.o 15-Apr-13 6:13am
   
You're welcome!
(may I ask you to vote if it has been useful to you ? thanks ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900