0

Does a static readonly field has only a single copy in memory no matter how many objects of its encapsulating type exist?

For example:

class A{
  static readonly SomeType foo;
  static A(){
    foo = new SomeType();
  }
...

So does foo exist only once in the whole program, no matter how many instances of A there are?

oɔɯǝɹ
  • 7,219
  • 7
  • 58
  • 69
shinzou
  • 5,850
  • 10
  • 60
  • 124
  • 1
    @oɔɯǝɹ , http://stackoverflow.com/questions/7095/is-the-c-sharp-static-constructor-thread-safe – jdphenix May 15 '16 at 19:48

1 Answers1

3

From ECMA-335 (emphasis mine)

I.8.4.3 Static fields and static methods

Types can declare locations that are associated with the type rather than any particular value of the type. Such locations are static fields of the type. As such, static fields declare a location that is shared by all values of the type. Just like non-static (instance) fields, a static field is typed and that type never changes. Static fields are always restricted to a single application domain basis (see § I.12.5 ), but they can also be allocated on a per-thread basis.

ThreadStaticAttribute allows for static allocation on a per-thread basis.

For most usual purposes, there would only be one instance of SomeType refrenced by foo in your snippet.

If you involve multiple application domains, or decorate it with [ThreadStatic], then multiple instances could possibly exist.

Community
  • 1
  • 1
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • So just to make sure, since it's shared by all values, it means that it's the same and it's created only once? – shinzou May 15 '16 at 19:20
  • Yes, it is shared by all values of `A`. Are you making a singleton? – jdphenix May 15 '16 at 19:22
  • Well I think it's a singleton yes, I need this field to be made only once in the program. – shinzou May 15 '16 at 19:25
  • If you use something like `static readonly Lazy foo = new Lazy(() => new SomeType())`, then later access `foo.Value`, you don't even need the static constructor there. .NET 4+ only. – jdphenix May 15 '16 at 19:51