0

I have been messing around with windows forms and I'm pretty new to C#. So you normally declare an instance like the following:Button example = new Button(); however, if the class Button is inside a namespace you must declare the fully qualified path: foo.bar.Button newButton = foo.bar.Button(); That works well as long as you know every fully qualified path you want to implement. However I stumbled with a situation in which you get the full qualified path from a string, therefore I'm not sure how to declare a new instance of the class.

private void treeLoader_Click(object sender, EventArgs e)
{
        string viewPath = this.tree.SelectedNode.FullPath;
        viewPath = viewPath.Replace(" ", "");
        viewPath = viewPath.Replace("\\", ".");
        // At this point viewPath equals "foo.bar.Button"

        Type newButton = Type.GetType(viewPath); // Failed attempt
}
  • Have a look at Activator.CreateInstance: https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=netframework-4.8 – David Libido Apr 16 '20 at 20:26
  • Are you asking about how to declare a variable of a type not-known-at-compile-time, or how to instantiate a type not-known-at-compile time? Your question seems to start with the former and then becomes the latter. Also, how is `Type.GetType()` failing? Have you looked at `Activator.CreateInstance()`? – Lance U. Matthews Apr 16 '20 at 20:27

0 Answers0