Blog Home  Home Feed your aggregator (RSS 2.0)  
What did you learn today? - Static Fields in Derived Types
Phil Denoncourt's Technology Rants
 
 Wednesday, October 08, 2008

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 3
inheritedClass 4

Instead, the output is
baseClass 4
inheritedClass 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.

Wednesday, October 08, 2008 8:08:08 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]   Development | DotNet  | 
Copyright © 2010 Phil Denoncourt III. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: