Language
Edit

CA2259: Attribute has no effect

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:

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.

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.

See also