Friday, March 02, 2001 ..:: Home ::.. Register  Login
   TechTidBits (Blog)  

Can you spot the error in this code?

Feb 19

Written by:
Thursday, February 19, 2009 9:48 PM  RssIcon

This afternoon I was writting some code which removed a ToolStripStatusLabel from my ToolStrip and it took me a few moments to figure it out.  Can you spot the error?

This afternoon I was whipping up some code for a new tool I'm writting at work and got myself into trouble with trying to be too smart.  DOH!  Can you spot the error?  (hint, it's not a syntax error but a logical one)

private void SetStatus( string message, EventLogEntryType messageType )
      using( ToolStripStatusLabel status = messageStatusLabel )
        status.Text = message;

          if( messageType == EventLogEntryType.Error )
            status.BackColor = Color.Red;
          else if( messageType == EventLogEntryType.Warning )
            status.BackColor = Color.Yellow;
            status.BackColor = SystemColors.Control;

If you're a C/C++ person or a guru with C# (SG? :>) you'll probably spot the problem immediately, but I was going on a few hours sleep and trying to be too smart with resources and hooped myself with this one.  I figured I would create one reference to the textbox I wanted to make changes to, like I used to do in VB many years ago.  Silly me, I already have that, it's the messageStatusLabel.  I was tired and I'm sticking with that excuse! :>

After running this piece of magic :> the textbox in the status strip disappeared. HUH? WTF? AAAAAHHHHHHHH!!!!!!!

Did you spot it yet?

If you're a VB coder (SB?) you might have an advantage about something just smelling with this code?

Did you spot the using statement up there? Getting smellier?

Here's a hint, what happens as the using's closing brace ('}') is processed? Figured it out yet?

Answer: :>  I think you'll like this one.:>  When the CLR processes the closing brace, the CLR runs the Dispose method on the using's object (status which is the messageStatusLabel), which effectively removes that object! POOF! Gone from the GUI, and gone from recent memory (well, until it's garbage collected, but it's still gone from the user's perspective).

So, uh, the question is why would I do that?  One I was tired, two, I was trying to be overly clever, and three I was trying something out like I used to do in the my old VB days.  Time bit me in the buttocks and I got hooped with this one.  Live and learn eh?  I hope you had some fun with this one.

Grab a coffee and get coding! :>



MSDN Magazine, 2007-11, CLR Inside Out, Managing Object Lifetime (look/search for ".NET Deterministic Finalization")

Location: Blogs Parent Separator TechTidBits

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Add Comment   Cancel 
Copyright 1999-2012 by   Terms Of Use  Privacy Statement