Why it is not possible to define generic indexers in .NET?

Viewed 22607

Why can't you create a generic indexer in .NET?

the following code throws a compiler error:

public T this<T>[string key]
{
    get => /* Return generic type T. */
}

Does this mean you can't create a generic indexer for a generic member collection?

7 Answers

Here's a place where this would be useful. Say you have a strongly-typed OptionKey<T> for declaring options.

public static class DefaultOptions
{
    public static OptionKey<bool> SomeBooleanOption { get; }
    public static OptionKey<int> SomeIntegerOption { get; }
}

Where options are exposed through the IOptions interface:

public interface IOptions
{
    /* since options have a default value that can be returned if nothing's
     * been set for the key, it'd be nice to use the property instead of the
     * pair of methods.
     */
    T this<T>[OptionKey<T> key]
    {
        get;
        set;
    }

    T GetOptionValue<T>(OptionKey<T> key);
    void SetOptionValue<T>(OptionKey<T> key, T value);
}

Code could then use the generic indexer as a nice strongly-typed options store:

void Foo()
{
    IOptions o = ...;
    o[DefaultOptions.SomeBooleanOption] = true;
    int integerValue = o[DefaultOptions.SomeIntegerOption];
}

I don't know why, but indexers are just syntactic sugar. Write a generic method instead and you'll get the same functionality. For example:

   public T GetItem<T>(string key)
   {
      /* Return generic type T. */
   }

Properties can't be generic in C#2.0/3.0 so therefore you can't have a generic indexer.

You can; just drop the <T> part from your declaration and it will work fine. i.e.

public T this[string key]
{
   get { /* Return generic type T. */ }
}

(Assuming your class is generic with a type parameter named T).

The only thing I can think of this can be used is something along these lines:

var settings = ConfigurationSection.AppSettings;
var connectionString = settings<string>["connectionString"];
var timeout = settings<int>["timeout"];

But this doesn't actually buy you anything. You've just replaced round parentheses (as in (int)settings["timeout"]) with angle brackets, but received no additional type safety as you can freely do

var timeout = settings<int>["connectionString"];

If you have something that's strongly but not statically typed, you might want to wait until C# 4.0 with its dynamic keyword.

Related