Is one copy of a public static variable created for each AppDomain in a process or is it just one copy for the whole process? In other words if I change the value of a static variable from within one AppDomain, will it affect the value of the same static variable within another AppDomain in the same process?
Asked
Active
Viewed 1,144 times
2 Answers
10
It is per application domain as proven by this example:
public class Foo
{
public static string Bar { get; set; }
}
public class Test
{
public Test()
{
Console.WriteLine("Second AppDomain: {0}", Foo.Bar);
}
}
class Program
{
static void Main()
{
// Set some value in the main appdomain
Foo.Bar = "bar";
Console.WriteLine("Main AppDomain: {0}", Foo.Bar);
// create a second domain
var domain = AppDomain.CreateDomain("SecondAppDomain");
// instantiate the Test class in the second domain
// the constructor of the Test class will print the value
// of Foo.Bar inside this second domain and it will be null
domain.CreateInstance(Assembly.GetExecutingAssembly().FullName, "Test");
}
}

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
1When I try and run the example program, I'm getting a TypeLoadException with message Could not load type 'Test' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. HResult is 80131522. – DWright Sep 08 '16 at 19:39
0
It is limited to the AppDomain, in other words, the variable exists as a separate value in each AppDomain.

driis
- 161,458
- 45
- 265
- 341