Search code examples
c#genericsexpression-trees

Expression<Func<in T, bool>> or Expression<Func<TBase,bool>> to Expression<Func<T,bool>> Converter


Is there any simple way to convert

Expression<Func<TBase,bool>> 

to

Expression<Func<T,bool>>

where T is inherited from TBase?


Solution

  • As long as T derives from TBase, you can directly create an expression of your desired type with the body and parameters of your original expression.

    Expression<Func<object, bool>> x = o => o != null;
    Expression<Func<string, bool>> y = Expression.Lambda<Func<string, bool>>(x.Body, x.Parameters);