manav inder
manav inder

Reputation: 3601

Cannot apply indexing to an expression of type 'T'

I've create a generic method like

public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
            where T : class

and in my class 'T' i've write indexer

public object this[string propertyName]
    {
        get
        {
            Type t = typeof(SecUserFTSResult);
            PropertyInfo pi = t.GetProperty(propertyName);
            return pi.GetValue(this, null);
        }
        set
        {
            Type t = typeof(SecUserFTSResult);
            PropertyInfo pi = t.GetProperty(propertyName);
            pi.SetValue(this, value, null);
        }
    }

now in my method when i write code like

var result = ((T[])(coll1.Result))[0];

string result= secFTSResult[propertyName];

I am getting the error Cannot apply indexing to an expression of type 'T'

Please help Thanks

Upvotes: 5

Views: 6794

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062865

Unless you use a generic constraint to an interface which declares the indexer, then indeed - that won't exist for abitrary T. Consider adding:

public interface IHasBasicIndexer { object this[string propertyName] {get;set;} }

and:

public void BindRecordSet<T>(IEnumerable<T> coll1, string propertyName)
        where T : class, IHasBasicIndexer 

and:

public class MyClass : IHasBasicIndexer { ... }

(feel free to rename IHasBasicIndexer to something more sensible)

Or a simpler alternative in 4.0 (but a bit hacky IMO):

dynamic secFTSResult = ((T[])(coll1.Result))[0];    
string result= secFTSResult[propertyName];

(which will resolve it once per T at runtime)

Upvotes: 9

Related Questions