Static Indexers

Static Indexers?

Indexer notation requires a reference to this. Since static methods don't have a reference to any particular instance of the class, you can't use this with them, and consequently you can't use indexer notation on static methods.

The solution to your problem is using a singleton pattern as follows:

public class Utilities
{
private static ConfigurationManager _configurationManager = new ConfigurationManager();
public static ConfigurationManager ConfigurationManager => _configurationManager;
}

public class ConfigurationManager
{
public object this[string value]
{
get => new object();
set => // set something
}
}

Now you can call Utilities.ConfigurationManager["someKey"] using indexer notation.

Are static indexers not supported in C#?

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.

Why no static indexers?

That's a good dupe reference there. Specifically, check out the answer :-)
Static Indexers?



Related Topics



Leave a reply



Submit