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
.
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:C#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()
{ }
}
.NET feedback
.NET is an open source project. Select a link to provide feedback: