Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression<Func<T, bool>> method argument

I'm trying to make a generic method that returns the string version of an expression:

public string GetExpressionString(Expression<Func<T, bool>> expr) where T: class
{
    return exp.Body.ToString();
}

Cannot resolve symbol T

Works well if I change T to a hard coded type.

What did I miss?

like image 667
Johan Avatar asked Jun 08 '26 14:06

Johan


1 Answers

You'll need to declare T as a generic type parameter on the method:

public string GetExpressionString<T>(Expression<Func<T, bool>> exp)
    where T: class
{
    return exp.Body.ToString();
}

// call like this
GetExpressionString<string>(s => false);
GetExpressionString((Expression<Func<string, bool>>)(s => false));

Or on the parent class:

public class MyClass<T>
    where T: class
{
    public string GetExpressionString(Expression<Func<T, bool>> exp)
    {
        return exp.Body.ToString();
    }
}

// call like this
var myInstance = new MyClass<string>();
myInstance.GetExpressionString(s => false);

Further Reading:

  • Generic Methods (C# Programming Guide)
like image 100
p.s.w.g Avatar answered Jun 11 '26 02:06

p.s.w.g