Monday, January 6, 2014

Copy list to new list, while adding new value to list overwrites previous value in the old list

List<T> Constructor (IEnumerable<T>):
Initializes a new instance of the List<T> class that contains elements copied from the specified collection.

Sample:
            List<string> col1 = new List<string> { "R1", "R2", "R3" };
            List<string> col2 = col1;

            col2.Add("R4");

            Console.WriteLine("Col1 Count is:" + col1.Count);
            Console.WriteLine("Col2 Count is:" + col2.Count);
            Console.ReadLine();

The OutPut is:
Col1 Count is:4
Col2 Count is:4

            List<string> col1 = new List<string> { "R1", "R2", "R3" };
            List<string> col2 =  new List<string>(col1);

            col2.Add("R4");

            Console.WriteLine("Col1 Count is:" + col1.Count);
            Console.WriteLine("Col2 Count is:" + col2.Count);
            Console.ReadLine();

The OutPut is:
Col1 Count is:3
Col2 Count is:4

No comments:

Post a Comment