PDA

View Full Version : Question on reflection



Bsbosa.com
07-15-2010, 09:41 PM
I assume that reflection is what I'd need for this but I can't seem to find the necessary information and thought I'd turn to CP.

Let's say I have a class with a few different member variables:
public class myClass
{
public int myInt;
public string myString;
public byte myByte;
}
Now I'd like to access one of the member variables in an instance of the class, based on a string variable available at run time. The following piece of code would do the job but, as you can imagine it would become very unwieldy if the class had a lot of member variables and I'd like to have it more generic anyway.
myClass myInstance = new myClass();
string whichMember;
string myValue;
.
.
.
switch (whichMember)
{
case "myInt": myValue = myInstance.myInt.ToString(); break;
case "myString": myValue = myInstance.myString; break;
case "myByte": myValue = myInstance.myByte.ToString(); break;
}