Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List and static variable behaviour in c#

Tags:

c#

I have a simple application in C#. When I ran the code I am not getting the expected result?.I am getting 2,2,1 but i was expecting 1,2,3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            MyList<int> list1 = new MyList<int>();
            MyList<int> list2 = new MyList<int>();
            MyList<double> list3 = new MyList<double>();
            Console.WriteLine(list1.GetCount());
            Console.WriteLine(list2.GetCount());
            Console.WriteLine(list3.GetCount());
        }
    }
    public class MyList<T>
    {
        static int _count;
        public MyList()
        {
            _count++;
        }
        public int GetCount()
        {
            return _count;
        }
    }
}
like image 867
santosh singh Avatar asked Dec 01 '10 17:12

santosh singh


1 Answers

The result is as I expect

2
2
1

This MSDN blog post tells

A static variable in a generic class declaration is shared amongst all instances of the same closed constructed type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply regardless of whether the type of the static variable involves any type parameters or not.

like image 151
Albin Sunnanbo Avatar answered Nov 03 '22 16:11

Albin Sunnanbo