Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

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 317 views
1 answer 213 views
1 answer 101 views
101 views asked Dec 14, 2020 by avibootz
2 answers 266 views
...