What about static indexers in C#?

Well, that’s not really possible but often people do ask if they can do this. Here’s a solution I recently gave someone which comes quite close which uses a singleton class instead of a static one:

class Test
{
    static Dictionary<int, string> map = new Dictionary<int, string>();

    private Test() { }

    private static Test instance = new Test();

    internal static Test Instance
    {
        get { return Test.instance; }
    }

    public string this[int i]
    {
        get
        {
            return map[i];
        }

        set
        {
            map[i] = value;
        }
    }
}

And here’s how you would use this:

Test.Instance[3] = "hello";
string s = Test.Instance[3];
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s