Welcome to AspAdvice Sign in | Join | Help

Orcs Goblins and .NET

I enjoy reading and writing. I hope you enjoy at least the former. I have moved my blog to Brendan.Enrick.com.

Syndication

Tags

News

Locations of visitors to this page

Navigation

Archives

Advice Sites

Articles

Blogs

Music

Return Within a C# Using Statement

While writing some code earlier today I needed to return from within a using statement. Doing these sorts of things always makes me appreciate the using statement and how wonderful it really is, so I decided to write about it here. As many of you know the using statement in C# is a good tool for managing types which will be accessing unmanaged resources. Some examples of these are SqlConnections, FileReaders, and plenty of other similar types. The key to these is that they all implement the IDisposable interface. This means that they all need to be cleaned up carefully after using them.

The using statement is great because it guarantees that the declared object is disposed no matter how the execution completes. Whether you reach the end curly brace marking the end of the using statement, throw and exception, or return from a function, the using statement will call the dispose method and clean up the object.

This was important in my code because I was able to return directly from within the using statement without worrying about whether or not eh dispose method will fire. Whenever I use an object which accesses unmanaged resources I always always always put it in a using statement.

It is very important to use a using statement, because it will give you this guarantee that the object will be disposed of correctly. The object's scope will be for the extent of the using statement, and during the scope of the object it will be read-only if defined in the using statement. This is also very nice, because it will prevent this important object which manages the unmanaged from being modified or reassigned.

This is safe to do, because of how great the using statement is. No matter which return we hit we know the XmlReader will be disposed of correctly.

using (XmlReader reader = XmlReader.Create(xmlPath))
{
    // ... Do some work...
    if (someCase)
        return 0;
    // ... Do some work...
    if (someOtherCase)
        return 1;
}
return -1;

Happy coding. Enjoy this powerful tool.

Update: I've posted a follow up to this post with a code sample. It shows that you can return from inside of a using statement in C#.

Sponsor

Published Thursday, May 22, 2008 9:38 AM by Brendan

Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Reflective Perspective - Chris Alcock » The Morning Brew #100 @ Friday, May 23, 2008 3:17 AM

PingBack from http://blog.cwa.me.uk/2008/05/23/the-morning-brew-100/

Reflective Perspective - Chris Alcock » The Morning Brew #100

# re: Return Within a C# Using Statement @ Friday, May 23, 2008 1:01 PM

I also like how the using block, via the dispose pattern can be used for non direct resource freeing, for instance TransactionScope. I have used it also for ensuring that code inside a using block runs under one user account and automatically reverts back to the original user once the using block has been completed.

Paul Kinlan

# re: Return Within a C# Using Statement @ Saturday, May 24, 2008 10:01 AM

I wrote a little bit more about the capabilities of the using statement which also is known as the IDisposable pattern in my link :)

Thomas Hansen

# re: Return Within a C# Using Statement @ Monday, May 26, 2008 3:17 AM

For me its like bad coding style to have return in multiple places..

Mantas

# re: Return Within a C# Using Statement @ Monday, May 26, 2008 11:12 PM

Good post, it is a good thing to know.

Sam

# re: Return Within a C# Using Statement @ Tuesday, May 27, 2008 9:24 AM

@Mantas I agree with you completely. I hate doing it, but in some rare circumstances it is much easier that the alternative. This example is just to show what can be done. I didn't actually use the above code. Thanks for the feedback.

Brendan

# re: Return Within a C# Using Statement @ Tuesday, June 17, 2008 7:52 PM

Thanks for this, I was looking for some verification that using and return play nicely together. I personally do not mind having multiple return statements in *some* of my functions. I think in can aid in readability in some situations.

Pete

# re: Return Within a C# Using Statement @ Wednesday, August 13, 2008 10:34 AM

I agree that having multiple return statements is often quite clearer than keeping a single local variable which may change meaning throughout the scope of the function. Indeed, the risks are as those known by global variables.

Stephen Swensen

# re: Return Within a C# Using Statement @ Friday, November 21, 2008 9:14 AM

I would like to ask you about how you verified that "using" is properly finished upon a "return" statement. Do you have any verification test, documentation or reference to prove your saying that "object is disposed no matter how the execution completes"? I am looking into MSDN and haven't found any such declaration. It just says about when an exception occurs, which doesn't mean "no matter how"! Regards, Lambros

Lambros

# re: Return Within a C# Using Statement @ Friday, November 21, 2008 9:44 AM

@Lambrose be careful there you took my quote out of context. What I said is "no matter how the execution completes". I am referring to cases when your application is still running because I say "completes", which implies that the program is able to stop. I then go on to state a couple of example cases where your application is still running in which the disposing will still be handled.

Obviously if your computer loses power the resources will not be disposed of. Basically as long as your application is able to stay alive even if it is throwing an exception the resources will be released. There is no way to handle the case where Windows crashes for example since nothing relating to your code or .NET is even running anymore.

Brendan

# re: Return Within a C# Using Statement @ Friday, November 21, 2008 5:02 PM

Dear Brendan, of course i don't expect resources to be released on a crash or any other situation of unexpected end of running. In MSDN (http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx) it declares that "A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement".

The above clearly says that resources are released if you reach the end or if an exception is thrown.

So, my concern about this issue is whether resources are released if we leave with a normal way (a "return" statement) before the end of the "using" block.

Regards, Lambros

Lambros

# Returning From Inside a Using Statement @ Saturday, November 22, 2008 10:28 AM

A while back I wrote a blog post regarding this topic. In that post I explain that it is safe to use a return statement inside a using block , because the using block will handle the disposing of the defined IDisposable object. This is one truly great

Brendan Enrick's Blog

# re: Return Within a C# Using Statement @ Saturday, November 22, 2008 10:29 AM

@Lambros Yes, the resources are released if you exit the using statement in a normal way. The using statement does work. I am posting a follow up to this with a short code example which shows this working. I posted it on my new blog. http://brendan.enrick.com/blog/returning-from-inside-a-using-statement/

Brendan

# Old Blog Favorites @ Wednesday, December 17, 2008 10:56 AM

I am somewhat partial to a few of the posts from my previous blog. For some of these posts, I just like the post, some the content about which the post was written, and some were just popular posts. Installing SQL Server Management Studio with SQL Server:

Brendan Enrick's Blog

# re: Return Within a C# Using Statement @ Tuesday, August 11, 2009 4:45 PM

What if you return the 'reader' object from within the using statement?

Rob

# re: Return Within a C# Using Statement @ Tuesday, October 27, 2009 11:17 AM

When control is passed out of the using block, the Dispose() method is called. So I'm pretty sure you'd end up with an ObjectDisposedException under most circumstances. Of course, the IDiposable interface is only have half of the (rather complex) Disposable pattern, so there could be some naughty object that will continue to function (or at least seem to) after disposal has been requested.

WCWedin

# re: Return Within a C# Using Statement @ Tuesday, August 24, 2010 2:15 PM

Lambros, He is correct. If you read the MSDN article for using Statement ( http://msdn.microsoft.com/en-us/library/yh598w02.aspx ), it shows the Using statement is the same as: { Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } } And looking at the return statment docuemntation( http://msdn.microsoft.com/en-us/library/1h3swy84.aspx ) "If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method." Since the dispose methods are in the Finally statment, all is good :)

Syndicate

# re: Return Within a C# Using Statement @ Monday, March 21, 2011 4:35 PM

@Syndicate Nice clarification. @Brendan Thanks for the article, it was a nice confirmation.

Zeroplex

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below