This documentation is archived and is not being maintained.

Compiler Error CS0313

Visual Studio 2008

The type 'type1' cannot be used as type parameter 'parameter name' in the generic type or method 'type2'. The nullable type 'type1' does not satisfy the constraint of 'type2'. Nullable types cannot satisfy any interface constraints.

A nullable type is not equivalent to its non-nullable counterpart. In the example that follows, ImplStruct satisfies the BaseInterface constraint but ImplStruct? does not because Nullable<ImplStruct> does not implement BaseInterface.

To correct this error

  • Using the code that follows as an example, one solution is to specify an ordinary ImplStruct as the first type argument in the call to TestMethod. Then modify TestMethod to create a nullable version of Implstruct in its return statement:

    return new Nullable<T>(t);
    

The following code generates CS0313:

// cs0313.cs
public interface BaseInterface { }
public struct ImplStruct : BaseInterface { }

public class TestClass
{
    public T? TestMethod<T, U>(T t) where T : struct, U
    {
        return t;
    }
}

public class NullableTest
{
    public static void Run()
    {

        TestClass tc = new TestClass();
        tc.TestMethod<ImplStruct?, BaseInterface>(new ImplStruct?()); // CS0313
    }
    public static void Main()
    { }
}
Show: