That is how static variables work.
"aL" is a static variable on
type TryTo. You only have one class called TryTo so there is only one aL variable (we'll call it TryTo.aL).
In this code
TryTo t1 = new TryTo();
TryTo t2 = new TryTo();
TryTo t3 = new TryTo();
t1, t2 and t3 are
instances of TryTo, and they have individual copies of all non-static fields. However when any of them interact with "aL" they are interacting with TryTo.aL, and there is only one TryTo.aL so every instance uses the same aL, therefore the same list.
The thing that can easily confuse is this line;
static System.Collections.ArrayList aL=new System.Collections.ArrayList();
you'd be forgiven for thinking that this initialisation happens every time you create a new instance of TryOne, but it doesn't, .net treats static instance declarations in a special manner and no matter how many times you create an instance of TryOne, the "= new ArrayList()" is only called the first time aL is used, this line is not called on each instance creation.
I've re-arranged your code a little, this might make it more obvious what is happening
class Program
{
static void Main(string[] args)
{
TryTo t1 = new TryTo();
t1.aLNonStatic.Add(1);
TryTo.aLStatic.Add(1);
t1.display();
TryTo t2 = new TryTo();
t2.aLNonStatic.Add(2);
TryTo.aLStatic.Add(2);
t2.display();
}
}
public class TryTo
{
public static System.Collections.ArrayList aLStatic = new System.Collections.ArrayList();
public System.Collections.ArrayList aLNonStatic = new System.Collections.ArrayList();
public void add(int i)
{
aLStatic.Add((object)i);
}
public void display()
{
Console.WriteLine("Static");
foreach (object i in aLStatic)
{
Console.WriteLine((int)i);
}
Console.WriteLine("Non Static");
foreach (object i in aLNonStatic)
{
Console.WriteLine((int)i);
}
Console.ReadLine();
}
}