diff --git a/docs/csharp/misc/cs0460.md b/docs/csharp/misc/cs0460.md index c80da435b4d9d..93633a953186f 100644 --- a/docs/csharp/misc/cs0460.md +++ b/docs/csharp/misc/cs0460.md @@ -1,7 +1,8 @@ --- description: "Compiler Error CS0460" title: "Compiler Error CS0460" -ms.date: 07/20/2015 +ms.date: 06/03/2025 +ai-usage: ai-generated f1_keywords: - "CS0460" helpviewer_keywords: @@ -12,11 +13,16 @@ ms.assetid: 98d39ded-d3f9-4520-b912-892e574c056b Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly - 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. + When a generic method that is part of a derived class overrides a method in the base class, you can't specify constraints on the overridden method. The override method in the derived class inherits its constraints from the method in the base class. + +However, there are exceptions to this rule: + +- Starting with C# 9, you can apply the `default` constraint to `override` and explicit interface implementation methods to resolve ambiguities with nullable reference types. +- 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. ## Example - The following sample generates CS0460. + The following sample generates CS0460 when attempting to redeclare inherited constraints. ```csharp // CS0460.cs @@ -30,12 +36,22 @@ interface I { void F1() where T : BaseClass; void F2() where T : struct; - void F3() where T : BaseClass; + void F3(); + void F4() where T : struct; } class ExpImpl : I { - void I.F1() where T : BaseClass {} // CS0460 - void I.F2() where T : class {} // CS0460 -} + // CS0460 - cannot redeclare inherited constraint. + void I.F1() where T : BaseClass { } + + // Allowed - explicit constraint for struct. + void I.F2() where T : struct { } + + // Valid since C# 8 - explicit class constraint for nullable annotations. + void I.F4() where T : struct { } + + // Valid since C# 9 - default constraint to resolve ambiguities. + void I.F3() where T : default { } +} ```