Jacob Carpenter’s Weblog

July 21, 2008

C# reminder of the day

Filed under: csharp — Jacob @ 4:24 pm

Static data is not shared among constructed generic types.

That is, the final line of output from the following program:

using System;

class Program
{
    static void Main()
    {
        NonGeneric.PrintCount(); // "Called 1 time."
        NonGeneric.PrintCount(); // "Called 2 times."

        Generic<int>.PrintCount(); // "Called 1 time."
        Generic<string>.PrintCount(); // ?
    }

    public static void DoPrintCount(int count)
    {
        Console.WriteLine("Called {0} time{1}.",
            count, count > 1 ? "s" : "");
    }
}

class NonGeneric
{
    public static void PrintCount() { Program.DoPrintCount(++count); }
    static int count;
}

class Generic<T>
{
    public static void PrintCount() { Program.DoPrintCount(++count); }
    static int count;
}

Is “Called 1 time.”

About these ads

5 Comments »

  1. The statement “Static data is not shared among constructed generic types.” is incomplete. It should read something like “Static data is not shared amongst instances of unique constructed generic types.” since the following is true

    Generic.PrintCount(); // “Called 1 time.”
    Generic.PrintCount(); // “Called 2 time.”

    Comment by Scott — July 21, 2008 @ 5:14 pm

  2. oops, i meant to include the generic int type argument

    Generic<int>.PrintCount(); // “Called 1 time.”
    Generic<int>.PrintCount(); // “Called 2 time.”

    Comment by Scott — July 21, 2008 @ 5:15 pm

  3. This is actually a great feature. It’s the reason why EqualityComparer.Default works.

    Comment by Dustin Campbell — July 22, 2008 @ 6:30 am

  4. Yeah; it totally makes sense why it’s the case. (Consider a static field of type T… that couldn’t possibly be shared among constructed types.) I just had sort of forgotten that it was the case. :)

    Comment by Jacob — July 22, 2008 @ 7:07 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: