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
}
}
}
}
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