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
  • What's the broader goal you're trying to accomplish? Commented Jul 5, 2012 at 10:18
  • 1
    @CodeCaster It is a duplicate if you assume the answer is going to be reflection, but there are other ways to do it that the linked answers don't cover. Commented Jul 5, 2012 at 10:40

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thanks @AlexeyF, you're absolutely right!
2

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

5 Comments

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: 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.
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: stackoverflow.com/questions/2783502/… And it doesn't work against his provided entity and assumes public member access.
You are right, @Adam, and thanks for sharing this cool link.
@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.