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;
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With