How can I dynamically get a property through a function in C #?

i has a function

public string getValue(string val)

and in this function I need to get the value from the database field:

using (UsersContext db = new UsersContext())
{
    UserProfile user = db.UserProfiles.Where(c => c.UserId == this.userId).FirstOrDefault()
    name = user.(val); ????????????
}

How can I get a custom value from a function argument? I think I need to change the type of the argument:

public string getValue(UserProfile val)

But how can I get a property or pass a property name?

Thank!!!:)

+4
source share
1 answer

As a rule, you easily pass a property as a function, not as a string, i.e. change your signature to

public string GetValue<T>(Func<UserProfile, T> property)

(.NET naming conventions are what methods should be in the Pascal Case.) With this, you can call name = property(user).

PropertyInfo . , .

+2

Source: https://habr.com/ru/post/1527712/


All Articles