Being primarily a C++ developer the absence of RAII (Resource Acquisition Is Initialization) in Java and .NET has always bothered me. The fact that the onus of cleaning up i
Brian Harry has a nice post about the rationales here.
Here is an excerpt:
What about deterministic finalization and value types (structs)?
-------------- I've seen a lot of questions about structs having destructors, etc. This is worth comment. There are a variety of issues for why some languages don't have them.
(1) composition - They don't give you deterministic lifetime in the general case for the same kinds of composition reasons described above. Any non-deterministic class containing one would not call the destructor until it was finalized by the GC anyway.
(2) copy constructors - The one place where it would really be nice is in stack allocated locals. They would be scoped to the method and all would be great. Unfortunately, in order to get this to really work, you also have to add copy constructors and call them every time an instance is copied. This is one of the ugliest and most complex things about C++. You end up getting code executing all over the place where you don't expect it. It causes bunches of language problems. Some language designers have chosen to stay away from this.
Let's say we created structs with destructors but added a bunch of restrictions to make their behavior sensible in the face of the issues above. The restrictions would be something like:
(1) You can only declare them as local variables.
(2) You can only pass them by-ref
(3) You can't assign them, you can only access fields and call methods on them.
(4) You can't box them.
(5) Problems using them through Reflection (late binding) because that usually involves boxing.
maybe more, but that's a good start.
What use would these things be? Would you actually create a file or a database connection class that can ONLY be used as a local variable? I don't believe anybody really would. What you would do instead is create a general purpose connection and then create an auto destructed wrapper for use as a scoped local variable. The caller would then pick what they wanted to use. Note the caller made a decision and it is not entirely encapsulated in the object itself. Given that you could use something like the suggestions coming up in a couple of sections.
The replacement for RAII in .NET is the using-pattern, which works almost as well once you get used to it.