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,859 questions

51,780 answers

573 users

How to create read only collection from int array in C#

2 Answers

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };

            numbers[4] = 10;
            ReadOnlyCollection numbers_readonly = Array.AsReadOnly(numbers);
            //numbers_readonly[3] = 60; // Error: numbers_readonly is read only collection

            for (int i = 0; i < numbers_readonly.Count; i++)
            {
                Console.WriteLine(numbers_readonly[i]);
            }
        }
        
    }
}

/*
run:
  
1
2
3
4
10

*/


answered Feb 26, 2015 by avibootz
0 votes
using System;
using System.Collections.ObjectModel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };

            numbers[4] = 10;
            ReadOnlyCollection numbers_readonly = Array.AsReadOnly(numbers);
            //numbers_readonly[1] = 120; // Error: numbers_readonly is read only collection
            numbers[3] = 89; // the int array: numbers is not read-only

            for (int i = 0; i < numbers_readonly.Count; i++)
            {
                Console.WriteLine(numbers_readonly[i]);
            }
        }
        
    }
}

/*
run:
  
1
2
3
89
10

*/


answered Feb 26, 2015 by avibootz
edited Feb 28, 2015 by avibootz

Related questions

...