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
Using the code that follows as an example, one solution is to specify an ordinary
ImplStruct
as the first type argument in the call toTestMethod
. Then modifyTestMethod
to create a nullable version ofImplstruct
in its return statement:return new Nullable<T>(t);
Example
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()
{ }
}
See also
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for