using in c#

Started by
1 comment, last by CProgrammer 19 years, 4 months ago
I just stumbled over this code: using (WinForm our_dx_form = new WinForm()) { Application.Run(our_dx_form); } Now Im curious as to what using is doing here and whats different between this and just WinForm our_dx_form = new WinForm(); Application.Run(our_dx_form); Im used to c++ and this doesnt tell me anything.
Advertisement
"using" is a special keyboard to use on items that implement the IDisposable interface. You can tell these classes because they have a Dispose() method in them to free / clean up resources. At the end of the using() {} statement, C# will call the object's Dispose() method.

So using your code, this is what happens:
using (WinForm our_dx_form = new WinForm()){     Application.Run(our_dx_form);}// our_dx_form.Dispose() is called because the item has gone out of scope.


You can also declare multiple items in the using statement like so:

using(Item one = new Item, Item two = new Item){     // Use them}// one.Dispose() and two.Dispose() are called because the items have gone out of scope.


Hope that's clear.
Thanks, that was a very helpfull explanation.

-CProgrammer

This topic is closed to new replies.

Advertisement