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"?
A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.) in a static 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With