NickG
NickG

Reputation: 9812

How can I make a collection which behaves like the Session[] collection? C#

I desperately need to mirror the behaviour of the Session collection in ASP.NET (in terms of it's behaviour when you retrieve items). I've spent a long time on this but have so far got nowhere.

A session is like a Dictionary except that if you access a Session and the value doesn't exist, you get null rather than it throwing an exception. This is all I need to duplicate.

I tried overriding the indexer to add a null check but it throws a stack overflow exception:

public class CriteriaCollection : Dictionary<string, object>
{
    private object GetData(string key)
    {
        object value = null;
        if (this.ContainsKey(key))
        {
            value = this[key];
        }
        return value;
    }

    private void SetData(string key, object value)
    {
        this[key] = value;
    }

    public new object this[string key]
    {
        get { return GetData(key); }
        set { SetData(key, value); }
    }
}

Upvotes: 2

Views: 85

Answers (1)

nvoigt
nvoigt

Reputation: 77304

As you have created your own indexer, you want to call the old indexer in your own code.

Replace this[key] by base[key] in your code.

Upvotes: 7

Related Questions