Another code snippet of the day

by Jon Sagara July 22, 2009 at 12:45 PM

Today's a good day. Check this out:

private static Dictionary<string, string> _dict = new Dictionary<string, string>();

static MyPage()
{
    //_dict.Add("item1", "val1");
    //_dict.Add("item2", "val2");
    //_dict.Add("item3", "val3");
    //_dict.Add("item4", "val4");
}

private void InitDictionary()
{
    try
    {
        _dict.Add("item1", "val1");
        _dict.Add("item2", "val2");
        _dict.Add("item3", "val3");
        _dict.Add("item4", "val4");
    }//END TRY
    catch
    {
        _dict.Clear();
        _dict.Add("item1", "val1");
        _dict.Add("item2", "val2");
        _dict.Add("item3", "val3");
        _dict.Add("item4", "val4");
    }//END CATCH
}

So what happened here? The guy decided that initializing the static dictionary variable in the static constructor wasn't good enough, and that he needed to do it on every page request, so he created an instance method to do the initialization. For some reason, though, he kept getting an exception when initializing the dictionary after the first page view. Hmm... bettter just swallow the exception, clear the dictionary, and try again.

*slaps forehead*

Tags: , , ,

Blog

Comments

7/30/2009 9:36:14 PM #

Jason

I think we all know static variables tend to become unset over time and that the only way to make sure they are set is keep setting them.  </sarcasm>

Jason United States

Comments are closed