Compiler Error CS0304
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
, 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 parameterless constructor. CS0304 occurs if you attempt to use the new
operator in the body of the class to create an instance of type parameter 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 parameterless constructor, that code will generate Compiler Error CS0310.
The following example generates CS0304.
// CS0304.cs
// Compile with: /target:library.
class C<T>
{
// The following line generates CS0304.
T t = new T();
}
The new
operator also is not allowed in methods of the class.
// Compile with: /target:library.
class C<T>
{
public void ExampleMethod()
{
// The following line generates CS0304.
T t = new T();
}
}
To avoid the error, declare the class by using the new()
constraint, as shown in the following example.
// Compile with: /target:library.
class C<T> where T : new()
{
T t = new T();
public void ExampleMethod()
{
T t = new T();
}
}
See also
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for