Is readonly variable thread safe?
c#, multithreading
Solution
A read-only variable is guaranteed to be initialized before it is accessed. The initial value is assigned during construction of the object, before the object is fully allocated.
Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.
Reference: C# Spec, 10.11.3 Constructor execution (emphasis mine)
Assignment to a readonly field can only occur as part of the field’s declaration or in a constructor in the same class
Reference: C# Spec, 1.6.5 Fields
For that reason, the value will be set before it is available to any thread, and will not change, so it is thread safe.
Problem
Possible Duplicate: Is a readonly field in C# thread safe? A quite simple program ``` private readonly string _data1; private readonly int _data2; private readonly MyAnotherClass _data3; public MyClass(string data1, int data2, MyAnotherClass data3) { _data1 = data1; _data2 = data2; _data3 = data3; } ``` Are `_data1, _data2 and _data3` thread safe?