Identifying class properties at runtime?

A

AdamM

At runtime, how do you take a user-supplied string, and then match that up
with a class property name?

For example, I have a User class with the property User.Name. At runtime, I
want the user to type 'set user.name=adam' and the code checks the user
class instance for the property name provided (Name) and assigns that value?

I cannot figure out how to do this without hardcoding the "set" code to know
the Name property in advance. As you can see, with every addition to the
User class, it would require changing the "set" code accordingly. I am
trying to avoid that by writing code that can figure out what properties are
available on a given class at runtime and interacting with them based on
user input.

Any tips? Thanks!
 
M

Mohammad

You could try:

string propertyName = "name";
object porpertyValue = ...; // The value you want to assign
Type t = user.GetType();
t.InvokeMember
( name
, BindlingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.SetProperty
, null
, user
, new object[] { propertyValue }
);

Watch out for exception though.
 
A

AdamM

Thanks Mohammad,

Does this code work on an existing class instance, or does it create a new
instance?

thx
 
M

Mohammad

Your welcome :)

It works on an existing class instance. The fourth argument named
"user", should be an existing class instance. So in your code, you'll
have to parse the string, get the name of the class instance, and use
that as the fourth argument to begin invoke. You would also extract the
property name, in your case "name", and also pass it as the first
argument. Finaly, extract the value, in your case "adam", and pass it
in an array of objects as the final argument.
 

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