Generic extension method for a safe item value fetch from HttpSessionState.

Posted Friday 9, October 2009, 8:46 in C#, ASP.NET

Hi there,

 

Here is an extension method for getting a value from the session in a safe manner.

 

   1: static public bool TryGet<T>(this HttpSessionState session, string key, out T value) {
   2:  
   3:     bool flag = false;
   4:     value = default(T);
   5:  
   6:     if (session != null) {
   7:         object objectValue = session[key];
   8:         if (flag = (objectValue != null && objectValue is T)) value = (T)objectValue;
   9:     }
  10:  
  11:     return flag;
  12: }

 

 

 

The usage is simple like:

 

   1: bool flag;
   2: if(this.Page.Session.TryGet<bool>("MyFlag", out flag)) {
   3:     // TODO value exists and can be used
   4: }

 

Regards