Is a readonly field in C# thread safe?
public class Foo
{
private readonly int _someField;
public Foo()
{
_someField = 0;
}
public Foo(int someField)
{
_someField = someField;
}
public void SomeMethod()
{
doSomething(_someField);
}
}
Have gone through some posts:
- What are the benefits to marking a field as readonly in C#? - JaredPar suggests that readonly fields once constructed are immutable and hence safe.
- Readonly Fields and Thread Safety, suggests that there is some risk if constructors do a lot of work.
So, if the readonly field is used as in the code above, and constructors are light, is it thread-safe? What if _someField is a referrence type (e.g. an array of strings)?