Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
There really is a single instance of a static field per appdomain. It kind of says this in the C# language reference, but not very explicitly. This knocked me around a little because I had assumed that there was a single static field per type within an appdomain. I had a base type that had a dictionary as a static field and assumed that each class that derived from it had its own instance of the static field. Not so…
Look at the following test code:
using System;using System.Collections.Generic;using System.Text;
namespace ConsoleApplication3{ class Program { static void Main(string[] args) { baseClass.AStaticValue = 3; inheritedClass.AStaticValue = 4; Console.WriteLine("baseClass {0}", baseClass.AStaticValue); Console.WriteLine("inheritedClass {0}", inheritedClass.AStaticValue); Console.ReadLine(); } } public class baseClass { public static int AStaticValue = 0; }
public class inheritedClass : baseClass {
} } }
I expected the results to be baseClass 3inheritedClass 4
Instead, the output isbaseClass 4inheritedClass 4
So unless you decorate the field with ThreadStatic or ContextStatic attributes, static means just one in an appdomain. Remember that when you are inheriting from objects that have static fields, there’s only one instance of that static field.