0

How can I refer to the properties of an object of type Employee, for example, dynamically? I'm after something like employee."hasBeenPaid"? Does it involve reflection?

class Employee
{
    String name;
    Bool hasBeenPaid;
}

2 Answers2

5

You could try:

Type type = your_class.GetType();
PropertyInfo propinfo = type.GetProperty("hasBeenPaid");

If you need the value

value = propinfo.GetValue(your_class, null);
Marco
  • 56,740
  • 14
  • 129
  • 152
  • 2
    And then propInfo.GetValue(your_object, null). Also Type.GetProperty has several arguments (BindingFlags at least) which allows you to get public or not public properties, static or non-static (instance), etc. – Alexey F Jul 05 '12 at 10:20
  • Thanks @AlexeyF, you're absolutely right! – Marco Jul 05 '12 at 10:26
2

You may use the dynamic C# feature; and yes, it will use reflection at runtime to resolve your properties.

Efran Cobisi
  • 6,138
  • 22
  • 22
  • 1
    Technically this won't work, the DLR will throw a runtime error about the accessibility of the properties (which are default private) and you cannot access this as "strings", but as coded duck-typed property names. – Adam Houldsworth Jul 05 '12 at 10:20
  • @Adam: the OP did not specify she need to retrieve the properties using strings and I think the C# dynamic feature could cover what she is looking for. – Efran Cobisi Jul 05 '12 at 10:33
  • The Question title specifically says "with a string" and the sample usage shows a string. Use of `dynamic` in it's basic form isn't enough to cover these requirements, use of a string also implies the ability to provide a variable instead of a literla. `dynamic` without any changes uses duck-typing, if you want to use strings you need to do something like this: http://stackoverflow.com/questions/2783502/c-sharp-using-the-dynamic-keyword-to-access-properties-via-strings-without-refle And it doesn't work against his provided entity and assumes public member access. – Adam Houldsworth Jul 05 '12 at 10:36
  • You are right, @Adam, and thanks for sharing this cool link. – Efran Cobisi Jul 05 '12 at 10:39
  • 2
    @DeeMac It is just a placeholder, there are no clues available as to your gender other than your last comment. Don't take it personally. – Adam Houldsworth Jul 05 '12 at 13:23