Thursday, May 5, 2011

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"?

From stackoverflow
  • 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.

    Joel Coehoorn : I tend to think of it in terms of "associated with the type _and_ shared among all instances".
    Brian Rasmussen : Jon you're too fast ... deleting my duplicate answer :(
    Jon Skeet : @Joel: But doesn't that still give a false sense that the instances have anything to do with it? You could argue equally validly that Test.x is shared among all instances of "string" as well :)
    Jeff Yates : I tend to think that static members have NOTHING to do with instances other than the type name and the access modifier handling, so I'm with Jon rather than Joel on this one.

0 comments:

Post a Comment