tags:

views:

336

answers:

5

I have a name of a property and need to find its value within a Class, what is the fastest way of getting to this value?

A: 

Just use the name of the property. If it is a nullable property (e.g. int ? property) use property.Value.

fbinder
The down vote was not fair because the question is not clear enough.
fbinder
+9  A: 

I am making the assumption that you have the name of the property in runtime; not while coding...

Let's assume your class is called TheClass and it has a property called TheProperty:

object GetThePropertyValue(object instance)
{
    Type type = instance.GetType();
    PropertyInfo propertyInfo = type.GetProperty("TheProperty");
    return propertyInfo.GetValue(instance, null);
}
Fredrik Mörk
You beat me to it. Note that the function need not have a parameter of a specific type however. `object instance` would do just fine, I believe.
Noldorin
@Noldorin: you are right about the input parameter; updated the code :o)
Fredrik Mörk
Perfect, I've just added the PropertName in the parameters so you can return any propertyname
Coppermill
A: 

At runtime you can use reflection to get the value of the property.

Two caveats:

  • Obfuscation: An obfuscator may change the name of the property, which will break this functionality.

  • Refactoring: Using reflection in this manner makes the code more difficult to refactor. If you change the name of the property, you may have to search for instances where you use reflection to get the property value based upon name.

Matt Brunell
+2  A: 

I assume you mean you have the name of the property as a string. In this case, you need to use a bit of reflection to fetch the property value. In the example below the object containing the property is called obj.

var prop = obj.GetType().GetProperty("PropertyName");
var propValue = prop.GetValue(obj, null);

Hope that helps.

Noldorin
+1  A: 

If you're interested in speed at runtime rather than development, have a look at Jon Skeet's Making reflection fly and exploring delegates blog post.

Dan Blanchard