Is it possible to refer to a member programatically (using a variable)?

E

Epson Barnett

Hi,
I'm new to C# and I'd like to be able to reference a field of an
object using a variable instead of literal text.

In the PHP scripting language, you can create a variable:
$var = "name";
and another variable:
$name = "Epson";

Then you can refer to $name, or $$var. They will equal the same thing.

Is there similar functionality in C#?

The reason:
I have a loop inside a function which accepts two parameters and tests
for equality - it tests if an objects property with the name of the
first parameter is equal to the second parameter. This is so I don't
have to hard code all possible properties in advance, or update it as
new properties are added.

string myprop = "Branch"; <-- I'd like to use this instead of the
literal text below:

foreach (string key in keys)
{
Product prod = (Product)collection[key];
if (prod.Branch != val)
{
collection.Remove(key);
}
}

Thanks,
Epson
 
J

Jan Tielens

Yes, this can be accomplished by using Reflection!

Look at the following code; it shows how to put a value in a dynamically
selected property of a textbox.

string propertyToSet = "Text";
System.Reflection.PropertyInfo pi;
pi = textBox1.GetType().GetProperty(propertyToSet);
pi.SetValue(textBox1,"Dynamically set!!", new object[] {});

First I declare a PropertyInfo variable (pi), and then I get an instance
using the GetProperty method of the Type class (which I got using the
GetType method of my TextBox). If I want to set the value, I use the
SetValue method of the pi object. The first parameter is the object for
which you want to set the value, the second is the actual value and the
third one is the index; which is in this case an empty array. If you want to
retrieve values instead of setting them, use the SetValue method. The same
can be done with methods and functions, then you have to use a MemberInfo
instead of a PropertyInfo object.

Let me know if you need more info!

--
Greetz

Jan Tielens
________________________________
Read my weblog: http://weblogs.asp.net/jan
 

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