You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly
13
+
Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except in specific cases
14
14
15
15
When a generic method that is part of a derived class overrides a method in the base class, you may not specify constraints on the overridden method. The override method in the derived class inherits its constraints from the method in the base class.
16
16
17
+
However, there are exceptions to this rule:
18
+
- Starting with C# 9, you can apply the `default` constraint to override and explicit interface implementation methods to resolve ambiguities with nullable reference types.
19
+
- Starting with C# 8, you can explicitly specify `where T : class` and `where T : struct` constraints on override and explicit interface implementation methods to allow annotations for type parameters constrained to reference types.
20
+
17
21
## Example
18
22
19
-
The following sample generates CS0460.
23
+
The following sample generates CS0460 when attempting to redeclare inherited constraints.
20
24
21
25
```csharp
22
26
// CS0460.cs
@@ -30,12 +34,19 @@ interface I
30
34
{
31
35
voidF1<T>() whereT : BaseClass;
32
36
voidF2<T>() whereT : struct;
33
-
voidF3<T>() whereT : BaseClass;
37
+
voidF3<T>();
38
+
voidF4<T>() whereT : struct;
34
39
}
35
40
36
41
classExpImpl : I
37
42
{
38
-
void I.F1<T>() where T : BaseClass {} // CS0460
39
-
voidI.F2<T>() whereT: class {} // CS0460
43
+
void I.F1<T>() where T : BaseClass {} // CS0460 - cannot redeclare inherited constraint
0 commit comments