10

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?

3
  • 4
    Your question is not clear. Can you show some code? How have you used a switch-case statement and a dictionary, and what do you mean by resolve dynamically? Commented Jun 20, 2012 at 14:55
  • 1
    What do you mean by "_datafile" to become _datafile ? Commented Jun 20, 2012 at 15:00
  • here is a code snippet along with the dictionary definition while (rdr.Read()) { string step = rdr.GetString(rdr.GetOrdinal("Step")); string tag = rdr.GetValue(rdr.GetOrdinal("Tag")).ToString(); string value = rdr.GetValue(rdr.GetOrdinal("Value")).ToString(); AddDataToWorkflow(step, tag, SearchDictionary(value)); } Commented Jun 20, 2012 at 17:39

3 Answers 3

12

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

this is partially working public static string _dataFile; string value = rdr.GetValue(rdr.GetOrdinal("Value")).ToString(); string result = this.GetType().GetField(value, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).GetValue(this).ToString(); this works with singular variables, now I have to get it to work with a collection for example: a collection of data named _parameters I would be looking to resolve _parameters.From etc.
Does the edit above answer your question?
3

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);

5 Comments

I don't think that will work as is. _datafile needs to be a property.
You should be able to do the same thing with properties. I've added one to my example.
Hmm yeah, it will work with DataFile, but not with _datafile. You should remove var f = typ.GetField("_datafile");
This code works in LinqPad but only if the field is public, so I'd agree that normally you wouldn't want to access a field this way. It depends on what the OP is trying to do though.
Ok my mistake, I thought it only worked with properties and not with fields. But it does indeed.
-1

Usually you would create a class representing the values of one table record. If your table has an ID a FirstName and a LastName column, you would 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 persons

var people = new List<Person>();

Now you can add persons to the list.

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

You can use a DataReader in order 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);
    }
}

1 Comment

It's not entirely clear, but I think this question is actually about reflection, not database access...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.