Click here to Skip to main content
15,892,517 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Why is it that C# indexers have to be instance members? Can they be static members too?
Posted
Updated 18-Feb-11 7:37am
v5

1 solution

No, but you can come pretty close. See this example:

C#
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;
        }
    }
}


Sample usage:

C#
Test.Instance[3] = "hello";
string s = Test.Instance[3];
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 18-Feb-11 13:03pm    
Sure, that's good, my 5.
I did not understand the question though.
What exactly "can not be"? Did you understand what it may mean?
Thank you.
--SA
Nish Nishant 18-Feb-11 13:26pm    
The OP was asking why C# does not support static indexers.
Sergey Alexandrovich Kryukov 18-Feb-11 14:25pm    
Indeed, not (I don't know why not, but syntax say "no statics"). Thank you for the answer; I did not read properly.
--SA
Nish Nishant 18-Feb-11 14:28pm    
I edited his question so it's clearer! :-)
Henry Minute 18-Feb-11 13:15pm    
Can I borrow your crystal ball, when you've finished with it, please Nish?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900