Get Property Value by Name - is it even possible

G

Guest

Hello,


Object instance is loaded into process with data in its Fields. There is a
db table, that dictates what properties values are needed for a stored
procedure call.
Is it possible to get value of a propery by its name?

so instead of this:

switch (propertyName)
{
case "AA" :
x = myObj.AA;
break;
//and so on
}

I want to do something like this:
x = myObj.PropertyValueGetter(propertyName);
 
B

Bruce Wood

Reflection is about it... why do you ask? Reflection is easy to use
once you get over the (small) learning curve. It does almost exactly
what you wrote:

PropertyInfo pi = myObj.GetType().GetProperty("AA");
x = pi.GetValue(myObj, null);
 
G

Guest

I was just asking if there was another "correct" way of doing it.
using reflections is not a problem for me at all.


Thank you
 
S

Steven Nagy

I think you'll find that reflection IS the correct way of doing it.

I would use attributes on desired properties.
For example, an 3 objects might represent 3 tables in a database.
Each of those objects has a different property for the PK: (eg.
obj1.userID obj2.UserAccessLevelID obj3.SalaryRatingID)
With an attribute called "PK" in front, you could get the value of the
primary key of any of those 3 objects without knowing the name of the
property even.

Of course you may no even be heading in this direction with your
design, so I'll just shut my big mouth.
 

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