Percy
Percy

Reputation: 3115

How can I create an object in a function using the string passed in C#?

I tried to search for an answer to this but I couldn't find one, the closest I found was: Create an instance of a class from a string but it doesn't really answer my question:

How do I create an instance of a class from a string, e.g. I want to create a WinForms object and add it to MDI.

I have a function that accepts a string, formname (e.g. "Form1"), and checks MDI children for an instance, if it exists it sets focus, if not then it creates an instance and adds it to the children.

The way I currently create a form is with a case statement but I will have to update this every time I add new Forms to the project! Is there a way of adding an instance of a Form class to the MDI children based on the string passed in, e.g. pseudo-code:

call to function: openForm("Form2");

public void openForm(String formname)
{
    if form exists in MDI children
    {
         focus form with name = formname;
    }
    else
    {
        MDIChildren.add(CreateInstanceOfClassNamed(formname));
    }
}

Upvotes: 1

Views: 177

Answers (3)

Servy
Servy

Reputation: 203802

Rather than passing a string you can just make the function generic:

public TForm GetForm<TForm>()
  where TForm : Form, new()
{
  TForm existingChild = MDIChildren.OfType<TForm>().FirstOrDefult();
  if(existingChild != null)
  {
    //focus, or do whatever
    return existingChild;
  }
  else
  {
    TForm newChild = new TForm();
    //do stuff with new child
    return newChild; 
  }
}

This will ensure that you don't pass the string value of a class that isn't a Form, or isn't of any type at all. You could call it like:

Form2 newChild = GetForm<Form2>();

Upvotes: 0

Botz3000
Botz3000

Reputation: 39600

try something like this (pseudocode, no clue about MDI stuff)

public void openForm(String formTypeName)
{
    Form FocusForm = null;
    Type formType = Type.GetType(formTypeName);
    foreach (var form in MDIChildren) 
    {
        if (form.GetType() == formType)
        {
             focusForm = form;
             break;
        }
    }
    if (focusForm == null)
    {
        MDIChildren.add(Activator.CreateInstance(formType));
    }
    // set focus to focusForm
}

Upvotes: 1

Mohsen Afshin
Mohsen Afshin

Reputation: 13436

Activator can create object from class name:

  object obj = Activator.CreateInstance(Type.GetType(assemblyname + "." +formname));

  ((Form)obj).ShowDialog();

Upvotes: 0

Related Questions