Static variablesin .Net , what is their life span?

In .NET, static variables are variables that belong to a class rather than an instance of that class. They are declared using the static keyword and are shared among all instances of the class. Unlike instance variables, which have a separate copy for each object, static variables have only one copy that is shared by all objects of the class.

Lifespan of a static variable

The lifespan of a static variable is tied to the lifespan of the application domain in which it resides. An application domain is a boundary that isolates running applications or components from one another. When the application domain is created, the static variables are initialized, and they remain in memory until the application domain is unloaded or the application exits. This means that static variables persist throughout the lifetime of the application, regardless of the number of instances of the class or the state of individual objects.

Here's an example to illustrate the concept of static variables:

public class Counter { private static int count; // Static variable public Counter() { count++; // Increment the static variable } public static int GetCount() { return count; // Access the static variable } } class Program { static void Main(string[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); int totalCount = Counter.GetCount(); Console.WriteLine("Total count: " + totalCount); // Output: Total count: 3 } }

In the above example, the Counter class has a static variable called count, which is incremented each time a new instance of the class is created. Since the count variable is shared among all instances, it keeps track of the total number of Counter objects created. When the GetCount method is called, it returns the current value of the static variable.


The static variable count retains its value across different instances of the Counter class, and its lifespan extends throughout the execution of the application.