3

I have class

public class Rule
{
    public int IdRule { get;set;}
    public string RuleName { get; set; }
}

I have List of Hashtable with values. Have key "idRule", "ruleName". Example

List<Hashtable> list = new Hashtable();
list["idRule"] = 1;
list["ruleName"] = "ddd";

I have function:

private static List<T> Equaler<T>(T newRule)
{
   var hashTableList = Sql.Table(NameTable.Rules); //Get table from mssql database
   var list = new List<T>();
   var fields = typeof (T).GetFields();

   foreach (var hashtable in hashTableList)
   {
       var ormRow = newRule;
       foreach (var field in fields)
       {
            ???what write this???
            // i need something like 
            //ormRow.SetValueInField(field, hashtable[field.Name])

       }
       list.Add(ormRow);
   }
   return list;
}

Call this function:

var rules = Equaler<Rule>(new Rule())

Question: How set value for variable if I know its string name?

1 Answer 1

5

You can use reflection to do this.

string value = hashtable[field];
PropertyInfo property = typeof(Rule).GetProperty(field);
property.SetValue(ormRow, value, null);

Since you know the type is Rule, you can use typeof(Rule) to get the Type object. But if you did not know the type at compile time you can also use obj.GetType() to get the Type object as well. There is also a complementary property PropertyInfo.GetValue(obj, null) which allows you to retreive the value with only the 'string' name of the property.

Reference: http://msdn.microsoft.com/en-us/library/xb5dd1f1.aspx

Sign up to request clarification or add additional context in comments.

3 Comments

Why not typeof(Rule).GetProperty(field) instead?
@OscarMederos Fixed and noted the difference between getting type object at compile time and runtime.
I mean in your example. You're still calling typeof(Rule).GetType() instead of just typeof(Rule).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.