Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Cannot create an instance of the variable type 'type' because it does not have the new() constraint
When you implement a generic class, and you want to use the new keyword to create a new instance of any type that is supplied for a type parameter T, then you must apply the new() constraint to T in the class declaration, as shown in the following example:
class C<T> where T : new()
The new constraint enforces type safety by guaranteeing that any concrete type that is supplied for T has a default, parameterless constructor. CS0304 occurs if you attempt to use new in your class definition to create an instance of T when T does not specify the new() constraint.On the client side, if code attempts to instantiate the generic class with a type that has no default constructor, then that code will generate Compiler Error CS0310.
The following sample generates CS0304. To avoid the error, declare the class as:
class C<T> where T : new()
// CS0304.cs
// Compile with: /target:library.
class C<T>
{
// Generates CS0304:
T t = new T();
}
The new statement of this form is also not allowed in class methods:
// CS0304_2.cs
// Compile with: /target:library.
class C<T>
{
public void f()
{
// Generates CS0304:
T t = new T();
}
}
See Also
Other Resources
C# Compiler Errors and Warnings
Change History
Date |
History |
Reason |
---|---|---|
August 2008 |
Added note showing how to avoid the error. |
Customer feedback. |
September 2008 |
Added additional explanatory text. |
Customer feedback. |