1

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is the constraint for a parameter-less constructor really that useful?
+1. @LightStriker, yes, it will allow to remove unnecessary reflection call to CreateInstance.
@AlexeiLevenkov: Actually, new T() compiles to Activator.CreateInstance. The constraint turns a runtime error into a compile-time error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.