shinzou
shinzou

Reputation: 6192

Does a static readonly field have only a single copy in memory?

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?

Upvotes: 0

Views: 269

Answers (1)

jdphenix
jdphenix

Reputation: 15425

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.

Upvotes: 3

Related Questions