How to access a property by its name

R

Rainer Queck

Hi NG,

how can I read/write a objects property, by just knowing ist Name as a
string?
Is there something like : myObject.GetPropertyByName("aName");

Thanks for help
 
C

Clive Dixon

Look at System.Type class and System.Reflection namespace:

myObject.GetType().GetProperty("aName").GetValue(myObject,null)

returns an object with the property value.

Similarly

myObject.GetType().GetProperty("aName").SetValue(myObject,value,null)
 
T

Tom Porterfield

Rainer said:
Hi NG,

how can I read/write a objects property, by just knowing ist Name as a
string?
Is there something like : myObject.GetPropertyByName("aName");

You need to use reflection for this. Ex:

Type t = myObject.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty("aName");
string name = pi.GetValue(myObject, null) as string;
 
R

Rainer Queck

Hi Peter,
Easy, eh?
Not that easy ;-)

For your understanding:
I have a "Class1" , that needs to access "some" property of "Class2" , but
on instantiation, it does not know which property that will be!

Some when later the owner of "Class1" tells the class by calling a method
like "Class1.ReadOtherClassProperty("<a property name>");
So now I need to know, how Class1 can read a Property from Class2 by only
knowing its "sting" name?

Rainer
 
R

Rainer Queck

Hi Tom,

Tom Porterfield said:
You need to use reflection for this. Ex:

Type t = myObject.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty("aName");
string name = pi.GetValue(myObject, null) as string;

Yes, like Clives hint.
Thanks for answering.

Rainer
 

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