Accessing a variable using a string containing the variable's name
c#, reflection, string, variables
Solution
Do you mean you want to get the value of a field using the field name as a string?
public class MyClass
{
public string _datafile;
public MyClass()
{
_datafile = "Hello";
}
public void PrintField()
{
var result = this.GetType().GetField("_datafile").GetValue(this);
Console.WriteLine(result); // will print Hello
}
}
EDIT: @Rick, to respond to your comment:
public class MyClass
{
public IEnumerable<string> _parameters = new[] { "Val1", "Val2", "Val3" };
public void PrintField()
{
var parameters = this.GetType().GetField("_parameters").GetValue(this) as IEnumerable;
// Prints:
// Val1
// Val2
// Val3
foreach(var item in parameters)
{
Console.WriteLine(item);
}
}
}
Problem
I am reading the name of a string variable from the database (e.g. "_datafile"). I want to know how I can access a named variable within my program using this string. I have already tried using a dictionary, hash table, and a switch-case statement but I would like to have the variable resolve itself dynamically. Is this possible?