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?
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);
}
}
}
If you want to get the value of a field based on its string name you will have to use reflection.
class MyClass
{
public int DataFile { get; set; }
public int _datafile;
}
var ob = new MyClass();
var typ = typeof(MyClass);
var f = typ.GetField("_datafile");
var prop = typ.GetProperty("DataFile");
var val = f.GetValue(ob);
var propVal = prop.GetValue(ob);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With