Jason Wicker
Jason Wicker

Reputation: 3456

Static Members of an Instance Class

Do static members of an instance class only live as long as the instance itself, or would the static member live throughout the life of the application?

For instance, say I have a Hashtable as a static property. If I added items to it from one "Instance" would they be available from another "Instance"?

Upvotes: 8

Views: 831

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503489

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.

Upvotes: 17

Related Questions