Skip to content

Latest commit

 

History

History
36 lines (26 loc) · 756 Bytes

File metadata and controls

36 lines (26 loc) · 756 Bytes

Pattern: Use of inline init for ThreadStatic field

Issue: -

Description

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

Example of incorrect code:

class TestClass
{
    [ThreadStatic]
    private static Object obj = new();
}

Example of correct code:

class TestClass
{
    [ThreadStatic]
    private static Object obj;

    static void TestMethod()
    {
        obj ??= new Object();
    }
}

Further Reading