Destructors and Finalization revisited

Most of the commentors on my destructors and finalizers post figured out the reason why we went with the destructor syntax – so that we could ensure that the base class destructor gets called. A few comments on the comments:

Jeroen Frijters has some comments on what’s wrong with C# finalization. It is true that there isn’t a guarantee across other languages that the right thing will happen here – this area and the whole Dispose() area are ones where it would have been nice to come up with a cleaner way to support these comments.

Finally, a comment on choosing the destructor syntax. It is true that we’re overloading the destructor syntax to mean something different (to some, subtly different) from what it means in C++. We did the same thing with the “new“ keyword – it means something different in C# than it does in C++.

I think we made reasonable decisions there. One could choose to make the opposite choice, but that would require you to come up with new keywords, which is a surprisingly hard thing to do (feel free to engage in discussion on what those should be in the comments).

Another question for the comments. Do you like the “why does C# do this?” format, or would you prefer me just to tell you why we do something?

Comments (2)

  1. Tom Welch says:

    Ultimately, the programmer is going to have to remember to do the things he HAS to do. My only thought here is to make what HAS to be done as straight-forward and consistent as possible. Since all CLR languages do not treat destructors in the same manner the problem has become inconsistent and obfuscated. In my opinion, it would have been much better for each class to override a Close() method from Object to close open resources before finalization or destruction.

    Besides, most of the time you need to Close() resources before letting the object sit in the GC pool awaiting destruction. ADO.NET XxxConnection classes are a prime example. Heaven help you if you forget to Close() explicitly.

    I applaud the decision to use the same keywords when there were subtle differences. The last thing we need is to try to explain that ‘create’ is just like ‘new’ except yada, yada, yada.

    As for the format, I greatly appreciate the "why does C# do this?" format. It gets the mind working. I’d rather try to figure it out, get it wrong, and then learn why rather than read something and take it for granted.

  2. Tom, I prefer having different keywords Close and Dispose. Classes that we are used to closing have a Close method in addition to Dispose.

    With the ADO.NET connection classes you mentioned, these classes have a different behavior with Close and Dispose.