Edit

Share via


Compiler Error CS0313

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 value 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

  1. 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:

    C#
    return new Nullable<T>(t);  
    

Example

The following code generates CS0313:

C#
// 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()  
    { }  
}  

See also