Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable using a string containing the variable's name [duplicate]

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?

like image 223
Rick Price Avatar asked Jun 20 '12 14:06

Rick Price


2 Answers

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);
        }
    }
}
like image 157
Kevin Aenmey Avatar answered Nov 18 '22 04:11

Kevin Aenmey


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);
like image 45
andrews_nz Avatar answered Nov 18 '22 03:11

andrews_nz