Field Name

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to retrieve a property value. I have a method which is being passed
(among other things) the "property name" in text format of the property that
I want to retrieve the value from. Is there some way to retrieve the
property value using the field which has the text name of the property to
retrieve. So for example, I know the property name is "Fred" and I am
passing that text to a method called "MyMethod("Fred")" (as generally
indicated below...)

Class FieldName
{
private string _Fred = "Here is your value";
public string Fred
{ get { return _Fred;}
}
}

..... Public string MyMethod (string nameOfProperty)
{
return FieldName.nameOfProperty;
}

Thanks in advance for your assistance.
 
using System.Reflection;

PropertyInfo p = this.GetType().GetProperty(PropertyName);
if(p != null) {
object value = i.GetValue(this, null);
}

this will work for getting a property dynamically from your own object ...
to make it work with any object just put it in a function and replace both
"this" with an instance to get the property value from.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 
Back
Top