Expression<Func> 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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:

Method 2

It’s a syntax error. You haven’t declared T as a generic type argument

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

notice the <T>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x