tags:

views:

457

answers:

2

Possible Duplicate:
Property Name and need its value

Hi,

This one should be easy for most people. I'd like to access a normal variable in an object (let's say example) by using a variable value.

E.g.: I have a an array with a list of variable names and I want to get the information from the object by using them. Obviously this is wrong:

string[] variable_names = new string[] {"name", "surname"};
myObject.variable_names[0] = 1; 
myObject.variable_names[1] = 1;

In other languages (not C#) I use:

myObject[variable_names[0]] = 1;

I know the example looks stupid but it was just a way of explaining it.

Thanks in advance :)

+3  A: 

C# is strongly type, this means that the compiler checks if the properties exist. So it is not as easy to dynamically access properties by name. You need to use reflection for this.

Instead of explaining how this works (I'm sure others will do this), I recommend to use an interface or another mean to provide the strong typing, whenever you can. C# is not a script language and should not be used as one.

Stefan Steinegger
+4  A: 

You will need to use Reflection to do this. Assuming that what you want to access is a property of myObject:

var type = myVariable.GetType();
var property = type.GetProperty("name");
property.SetValue(myVariable, 1, new object[] {});
John Saunders