Field Name

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.
 
G

Greg Young

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top