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:)

+1


a source to share


2 answers


For this you need Reflection. Assuming what you want to get is the myObject property:



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

      

+6


a source


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.

+2


a source







All Articles