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?
“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.
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.
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.
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]; }
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