Easy? Accessing an object using a variable in C #
Possible duplicate:
Property name and value
Hello,
This should be easy for most people. I would like to access a normal variable in an object (like example) using the value of the variable.
For example: I have an array with a list of variable names and I want to get information from an object 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 silly, but this is just a way to explain it.
Thanks in advance:)
a source to share
C # is strongly type, which means the compiler checks if the properties exist. Therefore, dynamically accessing properties by name is not easy. For this you need to use reflection.
Rather than explaining how it works (I'm sure others will), I recommend using an interface or some other tool to enforce strong typing whenever possible. C # is not a script language and should not be used as one.
a source to share