I have the following winforms classes:
class EntityEditorForm<T>: System.Windows.Forms.Form
where T: ICloneable<T> {}
class EntityCollectionEditorForm<T> : System.Windows.Forms.Form
where T: ICloneable<T> {}
The first form class is an editor for <T> that creates controls at run-time depending on the type of T.
The second is a manager for a collection of <T> and has Add, Edit and Delete functions. The collection is displayed in a listview control with fields populated through reflection using custom attributes.
The code for Add and Edit buttons looks like this:
private void buttonEdit_Click (object sender, System.EventArgs e)
{
T entity = default(T);
entity = (T) this.listView.SelectedItems[0].Tag;
new EntityEditor<T>(entity).ShowDialog(this);
}
private void buttonEdit_Click (object sender, System.EventArgs e)
{
T entity = new T(); //This is the code which is causing issues
entity = (T) this.listView.SelectedItems[0].Tag;
new EntityEditor<T>(entity).ShowDialog(this);
}
The default(T) works in the case of edit but I'm having trouble with the Add scenario. T entity = new T(); does not appear to be legal.
If your type contains an parameterless constructor, you can add a constraint onto your generic type T to allow instantiation through this parameterless constructor. To do this, add the constraint:
where T : new()
MSDN Article on Constraints on Type Parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With