How do I get the value of a MemberInfo
object? .Name
returns the name of the variable, but I need the value.
I think you can do this with FieldInfo
but I don't have a snippet, if you know how to do this can you provide a snippet??
Thanks!
How do I get the value of a MemberInfo
object? .Name
returns the name of the variable, but I need the value.
I think you can do this with FieldInfo
but I don't have a snippet, if you know how to do this can you provide a snippet??
Thanks!
Although I generally agree with Marc's point about not reflecting fields, there are times when it is needed. If you want to reflect a member and you don't care whether it is a field or a property, you can use this extension method to get the value (if you want the type instead of the value, see nawful's answer to this question):
Jon's answer is ideal - just one observation: as part of general design, I would:
The upshot of these two is that generally you only need to reflect against public properties (you shouldn't be calling methods unless you know what they do; property getters are expected to be idempotent [lazy loading aside]). So for a
PropertyInfo
this is justprop.GetValue(obj, null);
.Actually, I'm a big fan of
System.ComponentModel
, so I would be tempted to use:or for a specific property:
One advantage of
System.ComponentModel
is that it will work with abstracted data models, such as how aDataView
exposes columns as virtual properties; there are other tricks too (like performance tricks).Here's an example for fields, using FieldInfo.GetValue:
Similar code will work for properties using PropertyInfo.GetValue() - although there you also need to pass the values for any parameters to the properties. (There won't be any for "normal" C# properties, but C# indexers count as properties too as far as the framework is concerned.) For methods, you'll need to call Invoke if you want to call the method and use the return value.