so if the string name of a variable is passed into a method, I know which variable to use.
in the following example, the area I need help with is PrintVar(string)…turning the string argument into the variable…so that it prints out “here be variable 1” and “here be variable 2” respectively…Thanks!
class ReflectionTest
{
class MyObj
{
private string myvar;
public MyObj(string input)
{ this.myvar = input; }
public override string ToString()
{ return ("here be " + myvar); }
}
class MyClass
{
private MyObj var1;
private MyObj var2;
public MyClass()
{
var1 = new MyObj("variable 1");
var2 = new MyObj("variable 2");
}
public void PrintVar(string theVariable)
{
Console.WriteLine(theVariable);
}
}
static void Main()
{
MyClass test = new MyClass();
test.PrintVar("var1");
test.PrintVar("var2");
}
}
If you need to fetch things by name, then personally I’d start by using a dictionary in the internal implementation, i.e.
The other option would be reflection (
GetType().GetFields()):