Tags: , | Categories: Articles, Labs Posted by RTomlinson on 9/9/2009 2:01 AM | Comments (0)

Let me start by saying that I absolutely HATE Session in ASP.NET. In fact...no I don't...what I mean is that I HATE improper use of Session and I specifically hate when it's used randomly as a poor design choice, typically by insanely aweful developers, you know who you are!

I have in the past designed, and stole, session manager helper classes. Today I was playing around with the idea of returning a strongly typed object from session using a single static helper method. Hardly a life changing post but hopefully someone, somewhere might find it interesting/useful.

public class SessionManager
{
    public static T GetSessionValue<T>(string key, HttpContext context) where T : class
    {
        return context.Session[key] as T;
    }
}

The c# compiler will complain if you return "as T" without a class or method level type constraint. Hence the need for "where T : class".

And its use?

SessionManager.GetSessionValue<string>("Username", Context);

 

blog comments powered by Disqus