Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match String with the Class property Names

Tags:

c#

reflection

I have a class with lets say 5 Properties

Int32 Property1;
Int32 Property2;
Int32 Property3;
Int32 Property4;
Int32 Property5;

Now I have to set the values of only 3 three of those properties dynamically. so far is OK but my issue is I get those three property Names as strings on runtime. Lets say, something like this..

List<String> GetPropertiesListToBeSet()
{
   List<String> returnList = new List<String>();
   returnList.Add("Property1");
   returnList.Add("Property3");
   returnList.Add("Property4");
   retun returnList;
}

So Now,

 List<String> valuesList = GetPropertiesToBeSet();

 foreach (String valueToSet in valuesList)
 {
 // How Do I match these Strings with the property Names to set values
    Property1 = 1;
    Property3 = 2;
    Property4 = 3;
 }
like image 373
user3745020 Avatar asked Sep 04 '25 02:09

user3745020


2 Answers

You can do something like this. Properties is your class

        Properties p = new Properties();
        Type tClass = p.GetType();
        PropertyInfo[] pClass = tClass.GetProperties();

        int value = 0; // or whatever value you want to set
        foreach (var property in pClass)
        {
            property.SetValue(p, value++, null);
        }
like image 100
Pankaj Avatar answered Sep 06 '25 18:09

Pankaj


Let's say that the name of the class which contains them is Properties. You can use the GetProperty() method to get a PropertyInfo and then the SetValue() method:

Properties p = new Properties();
Type t = p.GetType(); //or use typeof(Properties)

int value = 1;
foreach (String valueToSet in valuesList) {
   var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; //because they're private properties
   t.GetProperty(valueToSet, bindingFlags).SetValue(p, value++); //where p is the instance of your object
}
like image 31
Omar Avatar answered Sep 06 '25 18:09

Omar