tags:

views:

125

answers:

3

How would I access an object's variable's value if I only have the name of the variable I wish to access? In C#.

Say I had a list of variable names represented as strings in an array. How would I access them in a loop, for example. I can do something like the following in Actionscript:

var arrayOfVariableNames:Array = ["name", "age", "sex"]

for each(var person:Person in persons)
{
    if (person[age] > 29)    //what is equivalent in c# for object[field]
    {
        //do something
    }
}
+1  A: 

The only way to get every variable in a list of variables is reflection over the object, however, you would end up with a group of values of type object, with no way of knowing the type of what's actually contained there (ie. you'd end up with a variable of type object for Name [string], Age [int], and Weight [int]). This makes reflection a poor way of getting a set of values from an object.

However, the general syntax to access a field is object.value, like this:

Person p = new Person ("John", 25, 160); // Name, age, weight (lbs)
Console.WriteLine ("Hello {0}!", p.Name); // Output: "Hello John!"

Note that this usage of Console.WriteLine is pretty much the same as using printf/fprintf in C and its ilk.

B.R.
+2  A: 

You can use reflection to access a field by its name :

FieldInfo ageField = typeof(Person).GetField("age");
int age = (int) field.GetValue(person);
Thomas Levesque
+2  A: 

If I correctly understood your question, you could do something like this:

class Person {
    private int age;
    private string name;
    private string sex;

    public object this[string name]
    {
        get
        {
     PropertyInfo property = GetType().GetField(name);
     return property.GetValue(this, null);
        }
        set
        {
     PropertyInfo property = GetType().GetField(name);
     property.SetValue(this, value, null);
        }
    }
}

It would solve your problem, but if my opinion matters, you should use normal properties instead, as you would lose type safety.

Fernando
+1 for solving the problem, -1 for implementing a sad API (not your fault, of course) for a net vote of 0.
Adam Robinson