7

The error message is "The type or namespace name 'T' could not be found."

???

public static Expression<Func<T, bool>> MakeFilter(string prop, object val)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    PropertyInfo pi = typeof(T).GetProperty(prop);
    MemberExpression me = Expression.MakeMemberAccess(pe, pi);
    ConstantExpression ce = Expression.Constant(val);
    BinaryExpression be = Expression.Equal(me, ce);
    return Expression.Lambda<Func<T, bool>>(be, pe);
}

Related links:

Using reflection to address a Linqed property

http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/df9dba6e-4615-478d-9d8a-9fd80c941ea2/

Runtime creation of generic Func<T>

Community
  • 1
  • 1
Axl
  • 8,272
  • 2
  • 26
  • 18

3 Answers3

10

You need to make the method itself generic:

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
                                                  -+-
                                                   ^
                                                   +- this
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
3

There's no generic argument defined for your method. You should define one (MakeFilter<T>):

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    PropertyInfo pi = typeof(T).GetProperty(prop);
    MemberExpression me = Expression.MakeMemberAccess(pe, pi);
    ConstantExpression ce = Expression.Constant(val);
    BinaryExpression be = Expression.Equal(me, ce);
    return Expression.Lambda<Func<T, bool>>(be, pe);
}
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
2

The method needs to be declared as generic (MakeFilter<T>):

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)

Otherwise, how else would the caller be able to specify what T is?

Rex M
  • 142,167
  • 33
  • 283
  • 313