static variables scope in C#

  • Thread starter Thread starter NewsMS
  • Start date Start date
N

NewsMS

I'd like to know if static variables have thread scope or process scope.
This means if the variable can be shared among threads on the same process
or is available only to different class instances on the same thread.

Thanks in advance.

Agustin Sanchez
 
NewsMS said:
I'd like to know if static variables have thread scope or process scope.
This means if the variable can be shared among threads on the same process
or is available only to different class instances on the same thread.

Neither - they have assembly scope. Anything using the same assembly
will see the same value (assuming the variable hasn't been decorated
with the ThreadStaticAttribute). If (somehow) you loaded two different
copies of the same assembly into the same AppDomain, I believe there
would be one copy of the variable for each of those assemblies.
 
Hi NewsMS,

Static variables have application-domain scope. Which means that they can be
shared by any threads in the same application domain. However if you have
more then one application domains running in the same process they cannot
share the same static variable. Each application domain hase its own copy of
the static variables hence, the same static variable in different domains
might have different value
 
You can declare a static class member (field), but "static" in C# has a
little bit different meaning than "static variable" in some procedural
languages. In C# a static member is shared by all instances of a class,
whereas a "static variable" as implemented in some languages is usually
meant to be associated with a single routine and just holds its value
between invocations. In other words the scope is different but the basic
idea is very similar.

--Bob
 
Bob Grommes said:
You can declare a static class member (field), but "static" in C# has a
little bit different meaning than "static variable" in some procedural
languages. In C# a static member is shared by all instances of a class,
whereas a "static variable" as implemented in some languages is usually
meant to be associated with a single routine and just holds its value
between invocations. In other words the scope is different but the basic
idea is very similar.

To be slightly more precise - the static member isn't so much shared by
all instances of a class, as unrelated to *any* of them. It belongs to
the class itself, rather than any instance, as it were. This means that
you don't even have to have a single instance in order to use the
static variable.
 
Back
Top