I came with another one. I happen to love Lambda expressions. The idea is to extend this base class:
public class SafeSessionBase<TSafeSessionImpl>
{
HttpSessionState _session;
public SafeSessionBase(HttpSessionState session)
{
_session = session;
}
protected TResult Get<TResult>(
Expression<Func<TSafeSessionImpl, TResult>> property)
{
var propertyName = GetMemberName(property);
return (TResult)(_session[propertyName] ?? default(TResult));
}
protected void Set<TValue>(
Expression<Func<TSafeSessionImpl, TValue>> property, TValue value)
{
var propertyName = GetMemberName(property);
_session[propertyName] = value;
}
private static string GetMemberName(Expression expression)
{
}
}
Your session then would look like this:
class MySafeSession : SafeSessionBase<MySafeSession>
{
...
public string StringProperty1
{
get { return Get(s => s.StringProperty1); }
set { Set(s => s.StringProperty1, value); }
}
public int IntProperty1
{
get { return Get(s => s.IntProperty1); }
set { Set(s => s.IntProperty1); }
}
...
}
Any property, of any type would work with this technique. Cast is included. This way supports refactoring. Unfortunately the framework session doesn't implement
IDictionary
(nor any other useful interface) thus, this implementation would only work for sessions. Remember, there is no parameterless contructor.
To use it:
private void Page_Load(object sender, EventArgs e)
{
...
_safeSession = new MySafeSession(Session);
if (_safeSession.HelloSafeSession == null)
_safeSession.HelloSafeSession = "Have a nice day. :)!!"
}
The almost forgotten method:
private static string GetMemberName(Expression expression)
{
LambdaExpression lambda = expression as LambdaExpression;
if (lambda == null)
throw new ArgumentNullException("expression");
MemberExpression memberExpr = null;
if (lambda.Body.NodeType == ExpressionType.Convert)
{
memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
}
else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpr = lambda.Body as MemberExpression;
}
if (memberExpr == null)
throw new ArgumentException("expression");
return memberExpr.Member.Name;
}