Generate dynamic object from dictionary with C # Reflection

Elton da Costa picture Elton da Costa · Aug 17, 2013 · Viewed 18.7k times · Source

I've been researching a bit about reflections in C # and would like to know if I use a dictionary with keys-values ​​can create an object with the variable with the name of each key in the dictionary and their values​​, the key value of that dictionary.

I have a method that does the opposite, that extracts an object from a dictionary, this dictionary contains the keys and the class properties and their values​​, the value of the properties.

I wonder how to do this if possible.

Below is my method, which extracts a dictionary of an object:

protected Dictionary<String, String> getObjectProperty(object objeto)
{
    Dictionary<String, String> dictionary = new Dictionary<String, String>();

    Type type = objeto.GetType();
    FieldInfo[] field = type.GetFields();
    PropertyInfo[] myPropertyInfo = type.GetProperties();

    String value = null;

    foreach (var propertyInfo in myPropertyInfo)
    {
        if (propertyInfo.GetIndexParameters().Length == 0)
        {
            value = (string)propertyInfo.GetValue(objeto, null);
            value = value == null ? null : value;
            dictionary.Add(propertyInfo.Name.ToString(), value);
        }
    }

    return dictionary;
}

Answer

Peter Ritchie picture Peter Ritchie · Aug 17, 2013

If you've already got a dictionary, I'd avoid reflection and just use DynamicObject

For example:

public class DynamicDictionary : DynamicObject
{
    private readonly Dictionary<string, object> dictionary;

    public DynamicDictionary(Dictionary<string, object> dictionary)
    {
        this.dictionary = dictionary;
    }

    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;

        return true;
    }
}

Which can be used as follows:

dynamic x = new DynamicDictionary(
    new Dictionary<string, object> {{"Name", "Peter"}});

Console.WriteLine(x.Name);