Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to set properties from a dictionary

I have an object with some properties and a dictionary which holds a temporary value for each of property. The key of this dictionary is a string with the same name of the property, while the value is an object.

What I want to do is to build a save method that reads the dictionary's keys and set the corresponding property to the value found in the dictionary.

So I thought about reflection but it's not as easy as I thought.

Here's a sample class:

public class Class{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
    public Dictionary<string, object> Settings { get; set; }

    public void Save()
    {
        foreach (string key in Settings.Keys)
        {
            // PSEUDOCODE
            get the property called like the key
            get its type
            get the value of hte key in the dictionary
            cast this object to the property's value
            set the property to the casted object
        }
    }
}

The reason why I'm not posting my code is beacuse I don't understand how to do casting and similar stuff, so I wrote a little bit of pseudocode to let you understand what I'm trying to achieve.

Is there anyone that can point me to the right direction?

like image 968
StepTNT Avatar asked Apr 26 '26 04:04

StepTNT


1 Answers

Here:

//Get the type
var type= this.GetType();

foreach (string key in Settings.Keys) 
{
    //Get the property
    var property = type.GetProperty(key);
    //Convert the value to the property type
    var convertedValue = Convert.ChangeType(Settings[key], property.PropertyType);
    property.SetValue(this, convertedValue); 
}

Not tested, but it should work.

like image 100
Alberto Avatar answered Apr 28 '26 18:04

Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!