CA2260: Implement generic math interfaces correctly
Property | Value |
---|---|
Rule ID | CA2260 |
Title | Implement generic math interfaces correctly |
Category | Usage |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As warning |
Cause
This rule fires when you implement a generic math interface that requires a self-recurring type parameter and you don't pass the type itself as the type parameter.
Rule description
Some generic math interfaces introduce static abstract members. The only way to access those static members is through a generic constraint that implements the "curiously recurring template pattern" (CRTP). Therefore, the derived type itself must be used for the self-recurring type parameter. If a type implements such an interface without passing the required type parameter and CA2260 is ignored, the code will compile successfully but the static abstract will not be accessible. Thus, the type will not be usable. The compiler emits a warning with ID CS0315 on such usage.
How to fix violations
Pass correct type parameter for self recurring type parameter (TSelf) when implementing those interfaces.
Example
Violation:
using System;
// Warns: The 'IParsable<TSelf>' requires the 'TSelf' type parameter to be filled with the derived type 'MyDate'
public readonly struct MyDate : IParsable<DateOnly>
{ ... }
Fix:
Pass the MyDate
type as the type parameter for the IParsable<TSelf>
interface.
using System;
// No warning
public readonly struct MyDate : IParsable<MyDate>
{ ... }
When to suppress errors
Do not suppress a warning from this rule.