7

As the title suggests, I am interested in when static classes are loaded into memory in .NET, C# in particular. I assume it is similar to this question in Java and this question regarding static methods, in that it is loaded the first time it is used. Additionally, once it is in memory does it stay there until the application terminates or does is get cleaned up when the garbage collector comes along to clean up the class that used it?

I realize the small amount of memory a static class uses is not terribly important in a world of computers that have 8+GB of RAM standard, but it is always interesting to know the internals.

Edit:

The answers led me want to add more to this question and to clarify with an example. If I understand correctly, in the example below Contraption.SomeString will be placed in memory first followed closely by Contraption.AnotherString with the first time through the loop.

public static class Contraption
{
    public static string SomeString = "Some String";
    public static string AnotherString = "Another String";
}

public class Processor
{
    public void Process(List<SomeClass> items)
    {
        foreach(var item in items)
        {
            if(item.Name == Contraption.SomeString)
            {
                //do something
            }
            if(item.Name == Contraption.AnotherString)
            {
                //do something
            }
        }
    }
}
Community
  • 1
  • 1
ninja coder
  • 1,067
  • 9
  • 22

3 Answers3

5

Regarding static fields initialization, an important point is the usage of static constructor. The CLR has a class loader component, which loads a class (metadata information) and request for memory allocation from the memory manager as they are used in the program. Metadata loading is one time job, post it just request memory on need basis

As understood in the discussion, the static class variables are loaded on the first usage of the class anywhere, and are assigned the memory, but using the static constructor can ensure that they are initialized as the first thing when class loader is invoked, its a one time call, which can do the initialization of all the static variables in a class, this even precede the first usage policy, as its when CLR (mscoree.dll) is components are loaded for a given program.

Static constructor is never called after first time under any circumstance (except program restart), even if there's an exception, its quite widely used, also static variables can be collected by setting them as null

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
  • so static do not allocate memory on compile time? but on the runtime when its first used? where does it get stored? STACK or HEAP? – Luminous_Dev Oct 29 '17 at 01:47
  • 1
    @Luminous_Dev stack and heap allocation are related to the value or reference type. This has nothing to do with Static / Non static – Mrinal Kamboj Nov 06 '18 at 01:49
2

I assume you're referring to fields within static classes (or static fields in non-static classes). They will be initialized before the first use. It's described in the C# specification:

10.4.5.1 Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

Static class members are considered Garbage Collection roots and all always reachable.

You can force the objects to be reclaimed by resetting the static member to null or other object:

public static class Foo 
{
    public static object Bar = new object();
}

// somewhere later
Foo.Bar = null;
// the object can be collected now.
Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Yes. I realized after I posted this that static classes are kind of pointless without their accompanying static members. – ninja coder Jan 14 '17 at 02:04
  • What is `new string("My first string here")` suppose to mean? – user4003407 Jan 14 '17 at 02:04
  • @PetSerAl There is some additional complexity related to literal strings and string interning. using `new string()` was meant to bypass that. I changed it to be an object instead to make it less confusing. – MarcinJuraszek Jan 14 '17 at 02:05
  • @MarcinJuraszek I am not about string interning. `System.String` does not have constructor accepting other string instance. If you want to make new string instance with same value, then you need to call [`Copy()`](https://referencesource.microsoft.com/mscorlib/a.html#dfd1cc49ace93169). – user4003407 Jan 14 '17 at 02:09
0

Static variables persist for the lifetime of an AppDomain, and in .NET, you can have multiple AppDoamins per application. Although most of the time, it is just one AppDomain per application, and other AppDomains are mostly created for sandboxing plugins.

https://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.110).aspx

Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44