Access a variable using a string containing the variable name

I am reading the name of a string variable from the database (for example, "_datafile"). I want to know how I can access a named variable in my program using this line.

I have already tried using a dictionary, a hash table and a switch-case statement, but I would like the variable to be solved dynamically by itself. Is it possible?

+7
source share
3 answers

Do you want you to get the field value 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); } } } 
+4
source

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); 
+2
source

Usually you should create a class that represents the values โ€‹โ€‹of a single table entry. If the table has an ID column FirstName and LastName , you should create a class like this

 public class Person { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } 

Then you create a list of faces

 var people = new List<Person>(); 

Now you can add people to the list.

 var p = new Person(); p.ID = 5; p.FirstName = "John"; p.LastName = "Doe"; people.Add(p); 

You can use DataReader to read from a table

 string sql = "SELECT * FROM tblPerson WHERE LastName LIKE @pattern"; cmd = new SqlCommand(sql); cmd.Connection = "server=test;uid=sa;pwd=manager;database=northwind"; cmd.Parameters.AddWithValue("@pattern", "A%"); // Names beginning with "A" using (SqlDataReader reader = cmd.ExecuteReader()) { // Get column indexes int idOrdinal = reader.GetOrdinal("ID"); int firstNameOrdinal = reader.GetOrdinal("FirstName"); int lastNameOrdinal = reader.GetOrdinal("LastName"); while(reader.Read()) { var p = new Person(); p.ID = reader.GetInt32(idOrdinal); p.FirstName = reader.GetString(firstNameOrdinal); p.LastName = reader.GetString(lastNameOrdinal); people.Add(p); } } 
0
source

All Articles