Reputation: 321
I have a function I want to make generic to display forms. I want the function to check if the form is opened already and if so bring it to the top if not create a new instance of the form and show it.
The first part of checking if the form is open is all good but I am having casting from T and creating a new form object of type T. I have used this line of code to create an instance of the form obj = Activator.CreateInstance<T>();
but it does not show all the methods and properties in intellisense. Where as the code Form x = new Form1.
x
will show all the methods and properties.
I am sure I am doing something wrong here any shine some light for me please.
private static void ShowForm<T>( )
{
T obj = default( T );
List<T> opened = FormManager.GetListOfOpenForms<T>();
if ( opened.Count == 0 )
{
// not opened
// obj does not show all properties and methods
obj = Activator.CreateInstance<T>();
// x shows all properties and methods
frmLogin x = new frmLogin();
}
else
{
// opened
}
}
Upvotes: 1
Views: 142
Reputation: 888185
You need to constrain T to inherit Form
:
private static void ShowForm<T>() where T : Form, new()
Once the compiler knows that T
is guaranteed to inherit Form
, you'll be able to use all members defined in Form
or its base classes.
The more general answer to your question would be to cast obj
to Form
.
Upvotes: 5