This documentation is archived and is not being maintained.

Compiler Error CS0304 

Error Message

Cannot create an instance of the variable type 'type' because it does not have the new() constraint

This error occurs if you use new to create an instance of a type variable when that type variable doesn't specify the new() constraint. You cannot use new to directly invoke the constructor for an unknown type unless the new() constraint is used to guarantee the existence of a default constructor. If you cannot use the new constraint, consider using a typeof expression to access the desired constructor.

The following sample generates CS0304:

// CS0304.cs
// compile with: /target:library
class C<T>
{
   T t = new T();   // CS0304
}

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()
   {
      T t = new T();  // CS0304
   }
}
Show: