Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic constructor: T entity = new T();

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.

like image 647
Raheel Khan Avatar asked May 17 '26 15:05

Raheel Khan


1 Answers

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.

like image 179
Samuel Slade Avatar answered May 20 '26 05:05

Samuel Slade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!