Home > Development > C# Abusing the Using statement for Fun and Profit

C# Abusing the Using statement for Fun and Profit

I did some digging around on the net and found cool uses for C#’s using statement. Here is an example of how roughly the using statement works when creating a form in ASP.NET MVC. Be aware this is an example and not actually how it works as this is sampleware 🙂

public class FormHelper : IDisposable
	public FormHelper (string method, string action)
		Console.WriteLine ("<form method=\"{0}\" action=\"{1}\">", method, action);

	public virtual void Dispose ()
		Console.WriteLine ("</form>");

using(FormHelper h = new FormHelper("GET","Test.aspx")){ }


  1. Phil
    June 23, 2010 at 12:55 pm

    Yep, that’s pretty much it.

    using (..) {… } is great for cleaning up resources on objects of limited scope. However, as with all .Net memory management, we’re not totally in control of when the disposal actually takes place. Its only “marked as ready to be disposed” when the block exits, and yes Dispose is guaranteed to be called (at some point).

    Note also that this form can only take one variable assignment, so to deal with multiple objects, you can nest the using statements (and I prefer to “stack” them at the same indentation level, for readability):

    using (FormHelper h = new FormHelper(“using!”))
    using (MemoryStream memoryStream = new MemoryStream())
    // stupid XmlSerializer doesn’t implement IDisposable!
    XmlSerializer serialzer = new XmlSerializer(typeof(FormHelper));
    serialzer.Serialize(memoryStream, h);

    (Of course, this is a useless example, as as soon as the block is exited, the memoryStream is no longer accessible, so we’ve lost everything we wrote to it! But I guess you get the idea!)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: