Compiler Error CS0304

Switch View :
ScriptFree
Visual Studio 2010 - Visual C#
Compiler Error CS0304

Updated: March 2011

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.

C#
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 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 CS0310.

The following example generates CS0304.

C#

// 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.

C#

// 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.

C#

// Compile with: /target:library.
class C<T> where T : new()
{
    T t = new T();

    public void ExampleMethod()
    {
        T t = new T();
    }
}

See Also

Other Resources

Change History

Date

History

Reason

March 2011

Revised the presentation of the examples.

Customer feedback.

Community Content

SJ at MSFT
How to instantiate generic type which has no default constructor?

Consider the following snippet:

    class Dong : IDong
{
public Dong()
{

}

public void Hit()
{
Console.WriteLine("Dong::Hit");
}
}

class Ding
{
public void One<TType>() where TType : class, IDong, new()
{
TType wuih = new TType();
wuih.Hit();
}
}

public static void Main()
{
Ding d = new Ding();
d.One<Dong>();
Console.ReadLine();
}


Question:
How can I instantiate NewDong class (see the snippet below) using a method that is similar to Ding::One?

    class NewDong : IDong
{
public NewDong(int yuhuu)
{

}

public void Hit()
{
Console.WriteLine("NewDong::Hit");
}
}

Thank you.



Edit by SJ at MSFT: You will have better luck with questions like this one in the forums, http://social.msdn.microsoft.com/Forums/en-US/categories. For example, you might try this one: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/threads.