I was recently tasked with adding a series of web pages to a huge existing site. Since I was new to the project, I wasn't privvy to all of the previously existing session variables, presenting quite the problem where naming a new Session
element was concerned. First, I gave all of my new session variables a prefix so I could at least guarantee (to some extent) that they would be unique to the module I was working on. However, the list of variables became extensive, not to mention the possibility of typing a name incorrectly, thus unintentionally creating another variable. To solve this issue, I came up with the following scheme.
In a word, it involves using an enum
. I simply define an enum
, like so:
public enum A00SessionVars { A00Value1, A00Value2, ... and so on };
And refer to it like this in the code:
Session(A00SessionVars.A00Value1.ToString())
Yes, it made for more typing, but I never once had anything unexpected happen as a result of spelling a name wrong, and it's impossible to add two variables that are the same name (with a deft bow of the head in the direction of C#'s case-sensitivity).
EDIT ==============
I was working on the code again today, and decided that using ToString()
was too clunky, so I came up with this:
Public T GetSessionVar<T>(A00SessionVars item, T defaultValue)
{
T value = defaultValue;
Object obj = Session(item.ToString();
if (obj == null)
{
SetSessionVar(item.ToString(), value);
}
else
{
value = obj as T;
}
return value;
}
Public void SetSessionVar(A00SessionVars item, Object value)
{
Session(item.ToString()) = value;
}
Public Function GetSessionVar(Of T)(ByVal item As G00SessionVars, ByVal defaultValue As T) As T
Dim value As T = defaultValue
Dim obj As Object = Session(item.ToString())
If (obj Is Nothing) Then
SetSessionVar(item.ToString(), value)
Else
value = CType(obj, T)
End If
Return value
End Function
Public Sub SetSessionVar(ByVal item As G00SessionVars, ByVal value As Object)
Session(item.ToString()) = value
End Sub
Now I can get/set just by doing this:
int i = GetSessionVar(A00SessionVars.A00Value1, -1);
string s = GetSessionVar(A00SessionVars.A00Value2, "N/A");
Dim i As Integer = GetSessionVar(A00SessionVars.A00Value1, -1)
Dim s As String = GetSessionVar(A00SessionVars.A00Value2, "N/A")
Now, I'm going to go back and see if anyone suggested this (I haven't read any of the alternatives or comments yet).