Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot apply indexing to an expression of type 'T'

Tags:

c#

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

like image 737
manav inder Avatar asked Jan 18 '23 22:01

manav inder


1 Answers

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)

like image 98
Marc Gravell Avatar answered Jan 31 '23 10:01

Marc Gravell