Språk
Merk
Tilgang til denne siden krever autorisasjon. Du kan prøve å logge på eller endre kataloger.
Tilgang til denne siden krever autorisasjon. Du kan prøve å endre kataloger.
| Property | Value |
|---|---|
| Rule ID | CA2259 |
| Title | Attribute has no effect |
| Category | Usage |
| Fix is breaking or non-breaking | Non-breaking |
| Enabled by default in .NET 10 | As warning |
| Enabled by default in .NET 11 | As warning |
| Applicable languages | C# and Visual Basic |
Cause
One of the following attributes is applied where it has no effect:
- ThreadStaticAttribute, ContextStaticAttribute, or FixedAddressValueTypeAttribute is applied to an instance field.
- FixedAddressValueTypeAttribute is applied to a static field whose type isn't a struct, or is a primitive type or an enum.
- SuppressGCTransitionAttribute is applied to a method that isn't a P/Invoke.
The rule also checks attributes that target the backing field of an auto-implemented property or a field-like event, such as [field: ThreadStatic].
Rule description
Some attributes only take effect in certain places. Anywhere else, the runtime ignores them, and the code doesn't do what it appears to do.
- ThreadStaticAttribute and ContextStaticAttribute only affect
static(Sharedin Visual Basic) fields. - FixedAddressValueTypeAttribute only affects
staticfields of a struct type that isn't a primitive type or an enum. - SuppressGCTransitionAttribute only affects P/Invoke methods.
The rule doesn't flag SuppressGCTransitionAttribute on methods whose interop source generator honors the attribute. These are methods marked with LibraryImportAttribute and the abstract instance methods of an interface marked with GeneratedComInterfaceAttribute.
How to fix a violation
To fix a violation, remove the attribute. If you meant the attribute to take effect, change the member so that it applies, for example by making the field static.
Example
The following code snippet shows violations of CA2259:
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
[ThreadStatic]
public int number = 404;
[FixedAddressValueType]
public static int s_count;
[SuppressGCTransition]
public static void DoWork() { }
}
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<ThreadStatic>
Public number As Integer = 404
<FixedAddressValueType>
Public Shared count As Integer
<SuppressGCTransition>
Public Shared Sub DoWork()
End Sub
End Class
When to suppress warnings
It's safe to suppress a warning from this rule. However, the attribute is a nop and is not doing what you intended it to do.