How to declare a fully qualified path to instanciate an object?

20 views Asked by At

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
}
0

There are 0 answers