Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic about "using" construct

Tags:

c#

.net

vb.net

If I use "using" construct, I know that the object gets automatically disposed. What happens if a statement inside an "using" construct raises an exception. Is the "using" object still disposed? If so, when?

like image 377
user203687 Avatar asked Oct 03 '10 05:10

user203687


People also ask

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

How hard is it to learn Visual Basic?

Visual Basic is the most widely used programming language for creating Windows applications. It is easy to learn and does not require you to memorize difficult commands like other programming languages.


2 Answers

A using block is converted - by the compiler - to this:

DisposableType yourObj = new DisposableType();
try
{
    //contents of using block
}
finally
{
    ((IDisposable)yourObj).Dispose();
}

By putting the Dispose() call in the finally block, it ensures Dispose is always called - unless of course the exception occurs at the instantiation site, since that happens outside the try.

It is important to remember that using is not a special kind of operator or construct - it's just something the compiler replaces with something else that's slightly more obtuse.

like image 190
Rex M Avatar answered Sep 19 '22 00:09

Rex M


This article explains it nicely.

Internally, this bad boy generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().

like image 40
Nayan Avatar answered Sep 20 '22 00:09

Nayan