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. will show all the methods and properties.
x
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
}
}
You need to constrain T to inherit
Form:Once the compiler knows that
Tis guaranteed to inheritForm, you’ll be able to use all members defined inFormor its base classes.The more general answer to your question would be to cast
objtoForm.