They live throughout the lifetime of the AppDomain
. (For Windows applications, that's usually the lifetime of the process; it may not be though, depending on exactly what you're doing. AppDomains
are recycled periodically in ASP.NET.)
Don't think of static variables as being shared between instances - think of them as belonging to the type rather than any particular instance. This makes it easier to understand how things work when you sometimes never create any instances.
For example:
class Test
{
static int x = 0;
static void Main()
{
x = 10;
Console.WriteLine(x);
}
}
There are no instances around to "share" Test.x
- but that's okay, because it's associated with the type Test
rather than with instances of Test
.
You could argue this is a pretty subtle distinction, but it's one I've found to be useful.