Compiler Error CS0311

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

The type 'type1' cannot be used as type parameter 'T' in the generic type or method '<name>'. There is no implicit reference conversion from 'type1' to 'type2'.

When a constraint is applied to a generic type parameter, an implicit identity or reference conversion must exist from the concrete argument to the type of the constraint.

To correct this error

  1. Change the argument you are using to create the class.

  2. If you own the class, you can remove the constraint or else do something to enable an implicit reference or identity conversion. For example, you can make the second type inherit from the first.

Example

// cs0311.cs
class B{}
class C{}
class Test<T> where T : C
{ }

class Program
{
    static void Main()
    {
        Test<B> test = new Test<B>(); //CS0311
    }
}

If this error occurs when trying to use a value-type argument, notice that an implicit numeric conversion, for example from short to int, does not satisfy a generic type parameter.

See Also

Reference

Community Content

Andrew in Surrey
Tip
When one of the constraints is an Interface, be sure that all of the required interfaces have been applied to the generic type parameter.

SFAF_IT
Derived Classes do not Implicitly convert
I have a class derived from ObjectContext and another derived from ObjectEntity; these derived classes (from the generated code, no less) do not implicitly convert and therefore cannot be used in as generic type parameters.