ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Session GetValue

A cleaner way to get values from Session

Source

using System;
using System.Web;

public static class HttpSessionStateBaseExtensions
{
    public static T GetValue<T>(this HttpSessionStateBase session, string key)
    {
        return session.GetValue<T>(key, default(T));
    }

    public static T GetValue<T>(this HttpSessionStateBase session, string key, T defaultValue)
    {
        if (session[key] != null)
        {
            return (T)Convert.ChangeType(session[key], typeof(T));
        }

        return defaultValue;
    }
}

Example

String value1 = Session.GetValue<String>("key1");
String value2 = Session.GetValue<String>("key2", "default text");

MyObject value3 = Session.GetValue<MyObject>("key3");
MyObject value4 = Session.GetValue<MyObject>("key4", new MyObject());

Author: Mark Wiseman

Submitted on: 28 mei 2014

Language: C#

Type: HttpSessionStateBase

Views: 7081