Thursday, May 16, 2024

Something about List item reference

     // Some differenent example 


            Base b1 = new Base() { Id = 1, Name = "base1" };

            Base b2 = new Base() { Id =2, Name = "base2" };

            Base b3 = new Base() { Id = 3, Name = "base3" };

            List<Base> lst = new List<Base> { b1, b2, b3 }; //b1 ,b2, b3 added to list

            Base b4 = new Base { Id = 4, Name = "base4" };

            PRintList(lst);


            var first= lst.Find(x => x.Id == 1); // fetching first item and chaging it by assigning new item.

            first = b4; //it will not affect list item

            PRintList(lst);

            

            lst[0] = b4; // now lost[0] will be b4.

            PRintList(lst);



            void PRintList(List<Base> lst)

            {

                foreach(Base b in lst) Console.WriteLine(   b.Id +" -"+ b.Name);

            }


            //Output:

            //1 - base1

            //2 - base2

            //3 - base3


            //1 - base1

            //2 - base2

            //3 - base3


            //4 - base4

            //2 - base2

            //3 - base3

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...