Skip to content

Commit d8238d3

Browse files
CopilotBillWagner
andcommitted
Update CS0460 documentation to include C# 8/9 constraint exceptions
Co-authored-by: BillWagner <[email protected]>
1 parent 2288d13 commit d8238d3

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

docs/csharp/misc/cs0460.md

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
description: "Compiler Error CS0460"
33
title: "Compiler Error CS0460"
4-
ms.date: 07/20/2015
4+
ms.date: 01/02/2025
55
f1_keywords:
66
- "CS0460"
77
helpviewer_keywords:
@@ -10,13 +10,17 @@ ms.assetid: 98d39ded-d3f9-4520-b912-892e574c056b
1010
---
1111
# Compiler Error CS0460
1212

13-
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
1414

1515
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.
1616

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+
1721
## Example
1822

19-
The following sample generates CS0460.
23+
The following sample generates CS0460 when attempting to redeclare inherited constraints.
2024

2125
```csharp
2226
// CS0460.cs
@@ -30,12 +34,19 @@ interface I
3034
{
3135
void F1<T>() where T : BaseClass;
3236
void F2<T>() where T : struct;
33-
void F3<T>() where T : BaseClass;
37+
void F3<T>();
38+
void F4<T>() where T : struct;
3439
}
3540

3641
class ExpImpl : I
3742
{
38-
void I.F1<T>() where T : BaseClass {} // CS0460
39-
void I.F2<T>() where T : class {} // CS0460
43+
void I.F1<T>() where T : BaseClass {} // CS0460 - cannot redeclare inherited constraint
44+
void I.F2<T>() where T : struct {} // CS0460 - cannot redeclare inherited constraint
45+
46+
// Valid since C# 8 - explicit class constraint for nullable annotations
47+
void I.F4<T>() where T : class {} // OK - explicit constraint for nullable annotations
48+
49+
// Valid since C# 9 - default constraint to resolve ambiguities
50+
void I.F3<T>() where T : default {} // OK - default constraint
4051
}
4152
```

0 commit comments

Comments
 (0)