Thursday, January 24, 2008

Generic Wrapper for Session variable in ASP.NET

I found a way to wrap around Session variable in ASP.NET. It provides a strong-type return type and make code much easy to understand.


Usage:

            GlobalAppParameter gp = GetSession<GlobalAppParameter>("gp", delegate {
                return GlobalAppParameter.NewGlobalAppParameter();
            });

Declare/implementation

        protected delegate T CallBack<T>();

        protected T GetSession<T>(string sessionName, CallBack<T> callBack ){

            T ret;
            if (Session[sessionName] == null)
            {
                ret = callBack();
                Session[sessionName] = ret;
            }
            else
                ret = (T) Session[sessionName];

            return ret;
        }

No comments: