Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexer constraint on generic types

Tags:

c#

indexer

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;
    }
like image 933
Svish Avatar asked Oct 23 '14 16:10

Svish


1 Answers

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.

like image 55
Servy Avatar answered Sep 30 '22 15:09

Servy