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

Code analysis

CA2019: `ThreadStatic` fields should not use inline initialization

Learn about code analysis rule CA2019: 'ThreadStatic' fields should not use inline initialization

CA2019 Reliability enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A field that's annotated with System.ThreadStaticAttribute is initialized inline or explicitly in a static (Shared in Visual Basic) constructor.

Rule description

System.ThreadStaticAttribute fields should be initialized lazily on use and not with inline initialization or explicitly in a static (Shared in Visual Basic) constructor. A static constructor only initializes the field on the thread that runs the type's static constructor.

How to fix a violation

To fix a violation, remove the inline or static constructor initialization. Instead, initialize the field on first use.

Example

The following code snippet shows a violation of CA2019:

csharp
class C
{
    [ThreadStatic]
    private static Object obj = new();
}
vb
Class C
    <ThreadStatic>
    Private Shared obj As New Object()
End Class

The following code snippet shows how to fix a violation:

csharp
class C
{
    [ThreadStatic]
    private static Object obj;

    static void S1()
    {
        obj ??= new Object();
    }
}
vb
Class C
    <ThreadStatic>
    Private Shared obj

    Shared Sub S1()
        If obj Is Nothing Then
            obj = New Object()
        End If
    End Sub
End Class

When to suppress warnings

It's safe to suppress a warning from this rule, but your app might exhibit unexpected behavior.

See also