Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static indexers not supported in C#? [duplicate]

Tags:

c#

.net

clr

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?

like image 447
Kilhoffer Avatar asked Sep 30 '08 19:09

Kilhoffer


People also ask

Can we have static indexer in C #?

You can't make a Static Indexer in C#… The CLR can, but you can't with C#.

Can indexers be overloaded?

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.

What is indexers in C sharp?

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.

Where are indexers used in C#?

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.


2 Answers

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.

like image 165
Jon Skeet Avatar answered Oct 15 '22 15:10

Jon Skeet


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")    
like image 44
Giorgi Chakhidze Avatar answered Oct 15 '22 16:10

Giorgi Chakhidze