Coppermill
Coppermill

Reputation: 6794

Property Name and need its value

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?

Upvotes: 1

Views: 3803

Answers (5)

Dan Blanchard
Dan Blanchard

Reputation: 4054

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.

Upvotes: 1

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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);
}

Upvotes: 18

Noldorin
Noldorin

Reputation: 147260

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.

Upvotes: 2

Matt Brunell
Matt Brunell

Reputation: 10389

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.

Upvotes: 0

Fabio Vinicius Binder
Fabio Vinicius Binder

Reputation: 13214

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

Upvotes: 0

Related Questions