Artem Community
Artem interactive communities
Generic extension method for a safe item value fetch from HttpSessionState.
del.icio.us Tags: ,

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


Posted 10-09-2009 8:46 by velio
Filed under: , ,
Powered by Community Server (Non-Commercial Edition), by Telligent Systems