tags:

views:

1116

answers:

4

I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?

A: 

An indexer will access some instance data. Static methods and properties may not access instance data so there's no point in having one.

Kon
Why couldn't a static indexer access static data?
Jonathan Allen
+17  A: 

No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider:

Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")

It would be relatively rarely used, I suspect, but I think it's odd that it's prohibited - it gives asymmetry for no particular reason as far as I can see.

Jon Skeet
Exactly. They have their place. Others on here talking about design issues clearly have never worked with a classic language that allowed, since they are very helpful.
Yep. My point exactly. They have a very useful place in architecture. Some people have their blinders on, I guess!
Kilhoffer
Crap. Now I gotta write a static method Cache.Get(key) instead of Cache[key]...
Gishu
A: 

If I understand the question, static indexers ARE supported for C# in general; it's just that not all classes IMPLEMENT them.

See this post as an example, with example code for implementing them. http://www.csharphelp.com/archives/archive140.html

Nikki9696
thats not true. the article you posted points out that they are not supported. did you read it?
I did, but apparently misunderstood. Thanks.
Nikki9696
+1  A: 

Although, you can simulate static indexers using static indexed properties:

public class MyEncoding
{
    public sealed class EncodingIndexer
    {
        public Encoding this[string name]
        {
            get { return Encoding.GetEncoding(name); }
        }

        public Encoding this[int codepage]
        {
            get { return Encoding.GetEncoding(codepage); }
        }
    }

    private static EncodingIndexer StaticIndexer;

    public static EncodingIndexer Items
    {
        get { return StaticIndexer ?? (StaticIndexer = new EncodingIndexer()); }
    }
}

Usage:

Encoding x = MyEncoding.Items[28591]; // Equivalent to Encoding.GetEncoding(28591)   
Encoding y = MyEncoding.Items["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")   
George Chakhidze