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?
You can't make a Static Indexer in C#… The CLR can, but you can't with C#.
Indexers can be overloaded. They are not equal to properties. Indexers allow the object to be indexed. Setting accessor will assign get and retrieve value.
Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.
In C#, indexers are created using this keyword. Indexers in C# are applicable on both classes and structs. Defining an indexer allows you to create a class like that can allows its items to be accessed an array. Instances of that class can be accessed using the [] array access operator.
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.
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")
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