Is it possible to create a generic class/method where the type must have an indexer?
My thought was to make the following two extension methods work on any type which uses an indexer for getting and setting values, but can't seem to find anything about it. Only stuff about making the indexer itself generic, which is not what I'm after...
public static T GetOrNew<T>(this HttpSessionStateBase session, string key) where T : new()
{
var value = (T) session[key];
return ReferenceEquals(value, null)
? session.Set(key, new T())
: value;
}
public static T Set<T>(this HttpSessionStateBase session, string key, T value)
{
session[key] = value;
return value;
}
There is no way to apply a generic constraint that the generic type argument have an indexer (or any operator). The best that you can do is create an interface with that restriction and restrict the generic argument to implementing that interface.
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