C#idiomatic C#
ca2259fundamentals/code-analysis/quality-rules

Code analysis

CA2259: Ensure `ThreadStatic` is only used with static fields

Learn about code analysis rule CA2259: Ensure 'ThreadStatic' is only used with static fields

CA2259 Usage enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

The System.ThreadStaticAttribute attribute is applied to an instance field.

Rule description

System.ThreadStaticAttribute, which indicates that the value of a field is unique for each thread, only affects static (Shared in Visual Basic) fields. When applied to instance fields, the attribute has no impact on behavior.

How to fix a violation

To fix a violation, remove the System.ThreadStaticAttribute attribute from the field.

Example

The following code snippet shows a violation of CA2259:

csharp
class C
{
    [ThreadStatic]
    public int number = 404;
}
vb
Class C
    <ThreadStatic>
    Public number As Integer = 404
End Class

When to suppress warnings

It's safe to suppress a warning from this rule. However, the [ThreadStatic] attribute is a nop and isn't doing what you intended it to do.

See also