Search code examples
c#listclassencapsulation

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


I created a class like this:

public class MyClass
 {
     public List<int> Params = new List<int>();

      public void Load(int data)
        {
            Params.Add(data);
        }
}

Then i initiate, let's say, three instances of the class.

MyClass one = new MyClass();
MyClass two = new MyClass();
MyClass three = new MyClass();

add the list with data:

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

then surprisingly when i check:

one.Params.Count();

the count is 3, also

two.Params.Count(); 

is also 3

each instance list got three numbers - i.e. the same list. Somehow instead of separated lists i got pointers to the same list. How would you make it into three different stand alone lists with each instance ?


Solution

  • Seems like nothing is wrong in the code you presented in the Original Post.

    Click here to see the live output for following code.

    using System.IO;
    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main()
        {
           MyClass one = new MyClass();
            MyClass two = new MyClass();
            MyClass three = 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 and Three.Params.Count are returning 1.

    As pointed out in comments, you are probably declaring Params as Static. In that case output will be 3 as all instance shares the same List.