Search code examples
c#winformsdictionaryreflectionmef

C# Set Dictionary<String, Object> Values using Reflection


I have the following working code, this open an form from a loaded .dll using assembly

Form main = (Form)CommandFacade.IModuleHandler.IHost as Form;
Assembly Assembly = (Assembly)IArticles.Assembly;
Type Type = Assembly.GetType("DAMS.Module.ARTICLES.Articles_Search", true);
Form Articles_Search = (Form)Activator.CreateInstance(Type) as Form;        
Articles_Search.MdiParent = main;
Articles_Search.StartPosition = FormStartPosition.CenterScreen;
Articles_Search.Show();

But i have declared 1 Dictionary (FormBehavior) in this Form and 1 List (HiddenColumns), i need to set values to this dictionary and add items to the List both using reflection. Normally i use this code but how i can do it using reflection?

Articles_Search.FormBehavior["Control"] = "Value";
Articles_Search.HiddenColumns.Add("article_cost");

This is the Article_Search Class:

public partial class Articles_Search : Form
{
    // Actions Vars
    public List<String> HiddenColumns = new List<String>();
    public Dictionary<String, Object> FormBehavior = new Dictionary<String, Object> { "Control", null } };
}

Solution

  • The property that you want to set using reflection is named Item:

    var itemPropertyInfo = dictionary.GetType().GetProperty("Item");
    

    There is a an overload to the SetValue method that accepts the parameter required by the Item property:

    itemPropertyInfo.SetValue(dictionary, value, new[] { key });
    

    Using reflection as explained is equivalent to executing the following code:

    dictionary[key] = value;
    

    Above is the general answer on how to set values in a dictionary using reflection. To answer your specific question which also involves a list and presumably private fields I provide this code:

    var formBehaviorFieldInfo = Articles_Search
      .GetType()
      .GetField("FormBehavior", BindingFlags.NonPublic | BindingFlags.Instance);
    var formBehavior = formBehaviorFieldInfo.GetValue(Articles_Search);
    var itemPropertyInfo = formBehavior.GetType().GetProperty("Item");
    itemPropertyInfo.SetValue(formBehavior, "Control", new[] { "Value" });
    
    var hiddenColumnsFieldInfo = Articles_Search
      .GetType()
      .GetField("HiddenColumns", BindingFlags.NonPublic | BindingFlags.Instance);
    var hiddenColumns = hiddenColumnsFieldInfo.GetValue(Articles_Search);
    var addMethodInfo = hiddenColumns.GetType().GetMethod("Add");
    addMethodInfo.Invoke(hiddenColumns, new[] { "article_cost" });