1

I'd like to call a property's method of an object through reflection. For instance,

var query = DataContext().SomeTable.Where(u => u.UserID.contains("P");

I've tried the following but no luck:

var query = DataContext().SomeTable.Where(u => u.GetType().GetProperty("UserID").Name.contains("P");

Which returns null. Please help.

user3496167
  • 165
  • 3
  • 10

2 Answers2

3

You have to get the value of u, then use ToString on it:

u.GetType().GetProperty("UserID").GetValue(u, null).ToString().Contains("P");

Of course it have be a little bit improved: check if GetValue do not return null etc.

Note: Remember that you can somewhere cache PropertyInfo obtained from u.GetType().GetProperty("UserID") so you won't have to call it every time.

Konrad Kokosa
  • 16,230
  • 2
  • 35
  • 57
3

You want GetValue, not Name

((string)u.GetType().GetProperty("UserID").GetValue(u) ?? "").Contains("P")

The use of the ?? operator here is just a safeguard to make sure that Contains doesn't throw an exception if UserID is null.

James
  • 77,877
  • 18
  • 158
  • 228