Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Members of an Instance Class

Tags:

c#

static

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

like image 402
Jason Wicker Avatar asked May 05 '09 19:05

Jason Wicker


People also ask

Can instance class have static members?

A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.) in a static class.

What are static members of a class?

When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.

When static members and instance members are created?

An instance data member of a class is recreated each time when a new instance of the class is created and it is associated with that instance only. Whereas a static data member of a class is not recreated with new instance creation, only one copy of it is shared by all the instances.

What is the difference between static and instance member of a class?

So, in summary, an Instance member is a member that belongs to an Instance of an object (in our example, the objects are c1 , c2 , and c3 ) whereas a static member belongs to the class itself and does not require an instance of an object as was demonstrated by making a call to CloneGenerator.


1 Answers

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.

like image 136
Jon Skeet Avatar answered Oct 23 '22 05:10

Jon Skeet