ReadOnlyCollection in CSharp

Introduction





ReadOnlyCollection<T> is a collection which wrap List<T> and do not allow any modification in it.

Any modification in List<T> will be reflected to the ReadOnlyCollection<T>.

We can present ReadOnlyCollection as below 


ReadOnlyCollection<T> readonlyvar=new ReadOnlyCollection<T>(<Collection Object>);


Description

To Understand ReadOnlyCollection we need to take an example. 


  • Take a list of Student Roll number.

            List<int> list = new List<int>();
            list.Add(1);
            list.Add(3);
            list.Add(5);


  • Take ReadOnlyCollection which wrap List object.


           ReadOnlyCollection<int> readonlyvar=new                                 ReadOnlyCollection<int>(list);

  • Try to print element from ReadOnlyCollection .

          foreach(int i in readonlyvar)
           {
                Console.WriteLine(i + " ");
           }

  • After that Insert a value in the middle of the list.

         list.Insert(1, 6);

  • Again try to print the ReadOnlyCollection.

        foreach (int i in readonlyvar)
         {
                
                Console.WriteLine(i + " " );
         }


Below is the complete program which explain ReadOnlyCollection.

        public static void Main()
        {
            //Can change to the list
            List<int> list = new List<int>();
            list.Add(1);
            list.Add(3);
            list.Add(5);
            //can not change to the collection
            ReadOnlyCollection<int> readonlyvar=new                                    ReadOnlyCollection<int>(list);
            foreach(int i in readonlyvar)
            {
                Console.WriteLine(i + " ");
            }
            Console.WriteLine("------------------------------------");
            //Any changes to the list will reflect to ReadOnlyColection              //as below
            list.Insert(1, 6);
            
            foreach (int i in readonlyvar)
            {
                
                Console.WriteLine(i + " " );
            }
            Console.ReadKey();
        }

Out-Put














Why We Need ReadOnlyCollection

  1. Readonlycollection stop allowing to modify the collection.
  2. It improve the performance of the application.
Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts