I want to create an object that will work in a similar way to ASP.Net Session.
Say I call this object mySession, I want to make it so when you do
mySession["Username"] = "Gav"
It will either add it to a database table if it doesnt exist or update it if it does. I can write a method to do this but have no idea how to get it to fire when used with the indexer syntax ([]). I've never built an object that does anything like this with indexers.
Before anyone says anything I know the ASP.Net session can save to database but in this case I need a slightly simpler customized solution.
Any pointers or examples of using indexers in this way would be great.
Thanks
It's actually pretty much the same as writing a typical property:
public class MySessionThing
{
public object this[string key]
{
//called when we ask for something = mySession["value"]
get
{
return MyGetData(key);
}
//called when we assign mySession["value"] = something
set
{
MySetData(key, value);
}
}
private object MyGetData(string key)
{
//lookup and return object
}
private void MySetData(string key, object value)
{
//store the key/object pair to your repository
}
}
The only difference is we use the keyword "this" instead of giving it a proper name:
public object MyProperty
^access ^(return) type ^name
modifier
public object this
^ditto ^ditto ^ "name"
Indexers in C# are properties with the name this
. Here's an example...
public class Session {
//...
public string this[string key]
{
get { /* get it from the database */ }
set { /* store it in the database */ }
}
}
From the MSDN documentation:
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
// Define the indexer, which will allow client code
// to use [] notation on the class instance itself.
// (See line 2 of code in Main below.)
public T this[int i]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal array.
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer.
class Program
{
static void Main(string[] args)
{
// Declare an instance of the SampleCollection type.
SampleCollection<string> stringCollection = new SampleCollection<string>();
// Use [] notation on the type.
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With