Casey Crookston
Casey Crookston

Reputation: 13955

Get value of item in object by variable name

Given some objects that looks like this:

public class MyObject 
{
    public int thing_1 { get; set; }
    public int thing_2 { get; set; }
    public int thing_3 { get; set; }
    ....
    public int thing_100 { get; set; }
}

How would I do something like this:

int valueINeed = GetValue(MyObject, 2);

Which would call... (and this is where I need the help)...

private int GetValue(MyObject, int find)
{
    return MyObject.thing_[find];
}

I'd rather not go line by line in a Switch, if that can be avoided.

Upvotes: 1

Views: 296

Answers (1)

rmojab63
rmojab63

Reputation: 3631

This might help:

var obj = new MyChildObject();
foreach(var prop in obj .GetType().GetProperties()) 
{
    if (prop.Name == "thing_" + find.ToString())
         return prop.GetValue(obj, null);
}

Upvotes: 3

Related Questions