How to use ReadOnlyCollection to makes an array or list read-only in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();

            list.Add(1);
            list.Add(2);
            list.Add(3);
            list.Add(4);
            list.Add(5);

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

            foreach (int n in roc)
                Console.WriteLine("roc: {0}", n);

            Console.WriteLine();

            //Error CS1061  'ReadOnlyCollection<int>' does not contain a definition for 'Add' 
            //roc.Add(6);

            int[] arr = new int[6];
            roc.CopyTo(arr, 0);

            foreach (int n in arr)
                Console.WriteLine("arr: {0}", n);

            Console.WriteLine();

            Console.WriteLine(roc.Count);
            Console.WriteLine(roc.IndexOf(2));
            Console.WriteLine(roc.Contains(999));
        }
    }
}

/*
run:
   
roc: 1
roc: 2
roc: 3
roc: 4
roc: 5

arr: 1
arr: 2
arr: 3
arr: 4
arr: 5

5
1
False

*/

 



answered Jan 19, 2017 by avibootz

Related questions

1 answer 326 views
1 answer 227 views
1 answer 112 views
112 views asked Dec 14, 2020 by avibootz
2 answers 279 views
...