Show/Hide Toolbars

XSharp

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 default, parameterless constructor. XS0304 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 default constructor, that code will generate Compiler Error XS0310.

 

The following example generates XS0304.

 

 

// XS0304.prg  
 

 

The new operator also is not allowed in methods of the class.

 

 

// Compile with: /target:library.  
 

 

 

To avoid the error, declare the class by using the new() constraint, as shown in the following example.

 

 

// Compile with: /target:library.