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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With