Search code examples
asp.nettype-safety

Type Safe Coding


When i started developing web applications i stored the authentication details of the user in two session variables

 Session["UserName"]="username";
 Session["Password"]="paswword-123";

But someone proposed me an idea to create a class which holds the UserName and Password properties and on succesful authentication i have been asked to create an instance of the class and set the UserName and Password properties and store that instance in the session.

I have been told that the session object is TypeSafe. Can someone explain what is typesafe coding and the advantage of storing the object in the session.


Solution

  • Basically, the classic approach of storing values directly in Session["something"] has two drawbacks:

    • Magic strings: If you mistype something, your code compiles fine but you get either a runtime error or, worse, an unnoticed bug in your code.
    • Casting: After reading Session["something"], you need to cast it to the type you need. (This is what is meant by "not type-safe".)

    Using a strongly-typed object that is stored in the Session eliminated the second problem. Well, actually, your custom object still needs to be cast, but it's only one cast instead of two (or ten) casts, which reduces the likelyhood of something going wrong. Again, a wrong cast is something which is only detected at run-time.

    Another approach is to encapsulate the access to Session variables in static properties:

    public class MySession {
        public static string UserName {
            get { return (string)HttpContext.Current.Session["UserName"]; }
            set { HttpContext.Current.Session["UserName"] = value; }
        }
    }
    

    Of course, both approaches can be combined, allowing you to group related properties (UserName and Password) in a common object.