Thursday, July 24, 2008

Yeah SessionTryParse

So I got tired of seeing If Session["SomeKey"] != null... blah blah blah and thought it would be a semi worthwhile task to create a TryParse method because I'm bad like that. Not a Bad Enough Dude to Save the President, but bad.
 public static Boolean SessionTryParse<K&gt;(HttpSessionState session, String key, out K itemToSet) where K : class
 {
     itemToSet = null;

     if (session[key] != null)
     {
        itemToSet = session[key] as K;
     }

     return itemToSet != null;
 }
And for structures... which I have to cheat and only allow them to be nullable.
public static Boolean SessionTryParse<K>(HttpSessionState session, String key, out K? itemToSet) where K : struct
{
     itemToSet = null;

     if (session[key] != null && session[key] is K)
     {
        itemToSet = (K)session[key];
     }

     return itemToSet != null;
}
The idea is simple, pull in the Session, the needed Session key, and something to throw the value in. After that, just check to see if the Session + Key is null and if Session + Key is the same type of said something. That's how it's done Detroit greater metropolitan area style... punk. USE THIS:
   using System;
   using System.Web.SessionState;

No comments: