in C# does Static constructor run for each initialization of object, or only once?

天涯浪子 提交于 2019-12-03 00:49:03

It runs once for the type, per AppDomain. Not once per instance. From the C# 4 spec, section 10.12:

The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  • An instance of the class type is created.
  • Any of the static members of the class type are referenced.

Note the part about it being per closed class. So if you have a generic type Foo<T>, then Foo<string> is a separate type to Foo<object> (etc), will have separate static fields, and will have its static constructor invoked separately.

It runs one time only during the lifetime of the application.

From MSDN - Static Constructors:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!