While I don't have answer I feel it's worth writing this up as an answer instead of just comments. The current answer with the most votes is as far as I know incorrect. According to Gordon Hogenson in Foundations of C++/CLI it does support "syntactic sugar or sleight of handle".... "To sum up, the heap-allocated object is immediately deleted at the end of the block, rather than lazily garbage collected, and as a consequence, the destructor is called immediately upon deletion." -emphasis mine, p 63 Stack vs. Heap Semantics
C++ programmers (pre smart pointers) are used to the fact that everything they new they must delete. However, when a C++ programmer creates a local variable, it does not have to be put on the heap. Stack semantics can be used and then the object doesn't have to explicitly deleted.
void Class::SomeMethod()
{
DbConnection connection; //No memory leak if not deleted
DbConnection leaky_connection = new DbConnection(); //on the heap will leak if not deleted
}
In C++/CLI it would look a little different for heap allocation:
DbConnection^ connection = gcnew DbConnection();
But since MS knew C++ programmers are used to stack semantics they allow the stack semantic version:
DbConnection connection;
And assuming the existence of :
~DbConnection()
{
//Close the connection
}
The stack semantic version will immediately call the destructor at the end of the method where connection is used.
I think the difficulty in doing this in C# is for the opposite of why it's allowed in C++/CLI (and here I may get into trouble). C# programmers are used to letting the garbage collector take care of things. They can allocate a local object stick it into a non-local container and not worry that it will go out of scope at the end of the method. The GC knows it's in the collection and it doesn't get prematurely destroyed. C# always deals with object references and you don't explicitly specify heap vs. stack storage. Implementing this "sleight of handle" in C# would probably break a lot of code and expectations.
In fact even the using statement syntax can create unexpected trouble in C#. I wrote up my favorite example of this in When Dispose Throws the Baby Out with the Bathwater a while back.
usingis still cleaner than the alternative (try/finally, blech)MyClassis a managed class that doesn't implementIDisposable?usingthat you lose with your preference (at least without further decoration)