Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
 Compiler Error CS0304

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
Visual C# Reference: Errors and Warnings
Compiler Error CS0304

Updated: August 2008

Error Message

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();  
   }
}

Date

History

Reason

August 2008

Added note showing how to avoid the error.

Customer feedback.

September 2008

Added additional explanatory text.

Customer feedback.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker