Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net define function that takes a lambda expression

I want to define a function like the MVC extension template function TextBoxFor

The interesting thing for that function is that I don't have to specify a TProperty type. How can I set that in my function definition.

My code look like:

public class Helper<TItem>
{
    public string GetMemberName(Expression<Func<TItem, TProperty>> expression)
    {
        ... returns TProperty.Name

    }
}

The actual problem is that this does not compile ... because it cannot find the TProperty type.

The result I want is to define the class once with a type ... and then use the function GetMemberName to get the name of each member like in MVC framework.

Helper<Employee> h = new Helper<Employee>();
string name = h.GetMemberName(e=>e.Name);
....

I don't want to be forced to specify the TProperty type when I write the code. Basically it can be any object.

Thanks,

Radu

like image 448
Radu D Avatar asked Apr 27 '26 08:04

Radu D


1 Answers

This is what you need:

public class Helper<TItem>
{
    public string GetMemberName<TProperty>(Expression<Func<TItem, TProperty>> expression)
    {
        return string.Empty; // I didn't implement it
    }
}

Just append <TProperty> to your method name to make it generic. And the type of TProperty can be inferred from provided expression, so you needn't to specify its type when using, can be simply:

Helper<Employee> h = new Helper<Employee>();
h.GetMemberName( e=>e.Name); //if Employee has such a property
like image 106
Cheng Chen Avatar answered Apr 29 '26 22:04

Cheng Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!