title: C# find already existing object instance using a string
body: <p>How can I the value of a string variable as an instance name?
  Here is some code:</p>
  
  <pre><code>    TabItem selectedTabItem = this.mainTabControl.SelectedItem as TabItem;
      Type t = selectedTabItem.DataContext.GetType();
      object instance = Activator.CreateInstance(t);
      MethodInfo method = t.GetMethod("SelectAll");
  
      //Here is the problem
      method.Invoke(t, null);
  </code></pre>
  
  <p>It exists 5 different classes (<strong>UserManager.cs, GroupManager.cs, PrinterManager.cs, FontManager.cs, ...)</strong> and everyone of these classes have the functions <code>SelectAll()</code>, <code>UnselectAll</code>, <code>RemoveSelected</code>. Now I dont want to create something like this: </p>
  
  <pre><code>        TabItem selectedTabItem = this.mainTabControl.SelectedItem as TabItem;
  
          if (selectedTabItem.Name == "UserManager")
          {
              if (btnSelectAll == pressed)
              {
                  this.UserManager.SelectAll();
              }
              else if (btnUnselectAll == pressed)
              {
                  this.UserManager.UnselectAll();
              }
              else if (btnRemoveSelected == pressed)
              {
                  this.UserManager.RemoveSelected();
              }
          }
          else if (selectedTabItem.Name == "PrinterManager")
          {
              if (btnSelectAll == pressed)
              {
                  this.PrinterManager.SelectAll();
              }
              //...
          }
          else if (selectedTabItem.Name == "GroupManager")
          {
  
          }
          //...
  </code></pre>
  
  <p>Now this line here:</p>
  
  <pre><code>method.Invoke(t, null);
  </code></pre>
  
  <p>It works fine, but I dont want to create a new instance. I need a existing instance. Now I could write </p>
  
  <pre><code>method.Invoke(this.UserManager, null);
  </code></pre>
  
  <p>But I think this way is not that good, because I will need again much if/else.</p>
  
  <p>I need something like this:</p>
  
  <pre><code>string instance = "this.UserManager";
  method.Invoke(instance, null);
  </code></pre>