I want to pass a property to a function such that the function knows both the value of the property and the name of the property. This is so I can return errors that match the property names.
I currently have code like this:
var userNameField = personField.GetChildField(f => f.UserName, nameof(personField.Value.UserName));
many times repeated, so the 2nd parameter is the name of the property inside the lambda of the 1st parameter.
Is it possible to automate this parameter so:
- The duplicate code is gone
- The string name of the property is calculated at compile-time, not run-time for every call
Ideally I would like my code to simply look like:
var userNameField = personField.GetChildField(f => f.UserName);
I have got this working using reflection using Expression<Func...
i.e. ((MemberExpression) getPropertyFunc.Body).Member.Name;
but this is too slow, in particular compiling the expression into a function which I can use to fetch the property value.
Similarly, I have read through the ideas here: Get name of property as a string
Is there any way of populating the property name from the GetChildField
function at compile time? Or encoding it into the model somehow?