C#C
C#5mo ago
VoidPointer

Use Lambda or Expression To Specify Property to Get Via Reflection

I have a prototype method for fetching a named property value from a model object:
// All properties on this model are strings just to simplify this question.
public string FindProperty(Guid key, string propertyName)
{
    var dbModel = kycRepo.KycExtraInformationRepo.Get(key);
    var prop = dbModel.GetType().GetProperty(propertyName);
    return prop.GetValue(dbModel, null);
}

I would like to avoid the caller having to provide the property name as a string, and instead somehow use a delegate, or some sort of expression construct, to specify an actual property on dbModel, where it would be called something like:
var pVal = FindProperty(Guid key, m => m.Surname)

Then I can either use the delegate to fetch the property value, or at least reflect on the delegate to get the property name and then again use reflection to get the property value.

What ways can I go about this?
Was this page helpful?