Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of new() while declaration of a generic class?

Tags:

c#

.net

generics

What is the purpose of new() while declaration of BaseEntityCollection class?
If I'm going to remove it, I got an error with the following message "T must be a non-abstract type with a public parameterless constructor in order to use it as parameter ..."

public abstract partial class BaseEntityCollection<T> : 
       List<T> where T : BaseEntity, new()
like image 907
Ahmed Atia Avatar asked Feb 18 '11 21:02

Ahmed Atia


1 Answers

Writing new() forces the parameter to have a default constructor.

Without it, you can't write new T().
Your error happens when you try to pass a non-new() type as a new()'d parameter.


Also, do not inherit List<T>.
Instead, you should inherit Collection<T>, which is designed for inheritance.

like image 198
SLaks Avatar answered Nov 15 '22 15:11

SLaks