views:

121

answers:

2

Is it possible to pass a generic type T into an instance of a winform so T is usable throughout the form?

+7  A: 

Yes, A Form is like any other class. You will have to modify the designer-generated code a little, and watch out that that does not get rolled back.

  // TestForm.cs
  public partial class TestForm<T> : Form

 // TestForm.Designer.cs
 partial class TestForm<T>
Henk Holterman
Note that generic forms can't be displayed in the Form Designer, though their dscendants can.
wRAR
@wrar, I was testing with VS2010 and that has no (obvious) problems with my TestForm. But I expect it to be a little feeble.
Henk Holterman
I am in the process of testing it out and will let you know how it works.
Nathan
A derived, concrete form won't be designable.
Hans Passant
Neither will a Derived generic Form.
Henk Holterman
+3  A: 

As suggested, this can be done - but in many cases you'll find yourself fighting the framework etc. IMO it may be simpler to just pass a Type into the form (as a property, perhaps), and instances via an object property (or an interface / base-class if such applies).

You can use generics, but in many cases in this scenario it won't actually help you much, and the designer hates it.

Marc Gravell
Marc, the VS2010 designer doesn't seem to have any problem with a Generic Form. It fails totally with Form-inheritance though.
Henk Holterman