Get Property Value by Name - is it even possible

  • Thread starter Thread starter Guest
  • Start date Start date
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);
 
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);
 
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
 
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.
 
Back
Top