c# - declaring a list inside a class and it's the same list in every instance? -


i created class this:

public class myclass  {      public list<int> params = new list<int>();        public void load(int data)         {             params.add(data);         } } 

then initiate, let's say, 3 instances of class.

myclass 1 = new myclass(); myclass 2 = new myclass(); myclass 3 = new myclass(); 

add list data:

one.load(10); two.load(50); three.load(100); 

then surprisingly when check:

one.params.count(); 

the count 3, also

two.params.count();  

is 3

each instance list got 3 numbers - i.e. same list. somehow instead of separated lists got pointers same list. how make 3 different stand alone lists each instance ?

seems nothing wrong in code presented in original post.

click here see live output following code.

using system.io; using system; using system.collections.generic;  class program {     static void main()     {        myclass 1 = new myclass();         myclass 2 = new myclass();         myclass 3 = new myclass();          one.load(10);         two.load(50);         three.load(100);          system.console.writeline("one.count  " + one.params.count);         system.console.writeline("two.count " +two.params.count);         system.console.writeline("three.count  "+ three.params.count);     } }  public class myclass  {      public list<int> params = new list<int>();        public void load(int data)         {             params.add(data);         } } 

all one.params.count, two.params.count , three.params.count returning 1.

as pointed out in comments, declaring params static. in case output 3 instance shares same list.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -