Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

generics

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?

like image 742
Igor Zelaya Avatar asked Jan 30 '09 07:01

Igor Zelaya


People also ask

Which keyword is used to declare indexers?

“this” keyword is always used to declare an indexer. To define the value being assigned by the set indexer, ” value” keyword is used. Indexers are also known as the Smart Arrays or Parameterized Property in C#. Indexer can't be a static member as it is an instance member of the class.

Why do we use indexers in C#?

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.

What's an indexer in C#?

C# Indexers An indexer is a special type of property that allows a class or a structure to be accessed like an array for its internal collection. C# allows us to define custom indexers, generic indexers, and also overload indexers.


1 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]; } 
like image 148
Sam Harwell Avatar answered Sep 21 '22 17:09

Sam Harwell