locked
How to convert System.Type to Form ? RRS feed

  • Question

  • Hi
    How to convert System.Type to Form ?

    i wrote this code :

    FormsCollection forms = new FormsCollection();
    foreach(Type t in types)
    {
    if (t.BaseType == typeof(Form))
    {
    Form frm = (Form)t;
    forms.Add(frm);
    }
    }


    but, the following error message display :

    Cannot convert type 'System.Type' to 'System.Windows.Forms.Form'

    How to solve this problem ?
    Thanks
    this is my Signature
    Thursday, April 16, 2009 3:40 PM

Answers

All replies

  • Use Activator.CreatInstance to create an instance of the Type.
    Thursday, April 16, 2009 3:52 PM
  • How can you typecast a Type object to Form?

    Identify the objects whose BaseType is Form and typecast those to Form.

    that means types should not be a collection of Type.
    _____________

    Guna
    Hope It Works, Guna
    Thursday, April 16, 2009 4:12 PM
  • You would do the following:

    if (t.BaseType == typeof(Form))
    {
        // Form frm = (Form)t;
        Form frm = (Form)Activator.CreateInstance(t);
        forms.Add(frm);
    }

    Activator.CreateInstance lets you create an instance of an object from it's type.  For details, see:

    http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

    • Marked as answer by Hamed_1983 Thursday, April 16, 2009 6:19 PM
    Thursday, April 16, 2009 4:41 PM