Alex Rivera | Logout

Is a readonly field in C# thread safe?

Asked 2011-11-27T14:23:17.180
25

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:

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)?

Edit
Report

1 Answer

25

Yes - your code doesn't expose this within either constructor, so no other code can "see" the object before it's been fully constructed. The .NET memory model (as of .NET 2) includes a write barrier at the end of every constructor (IIRC - search Joe Duffy's blog posts for more details) so there's no risk of another thread seeing a "stale" value, as far as I'm aware.

I'd personally still usually use a property instead, as a way of separating implementation from API, but from a thread-safety point of view it's fine.

answered 2011-11-27T14:29:18.303

Your Answer