How to create a read only IList in C#

1 Answer

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

public class Test  {

   public static void Main()  {

        String[] arr = { "c#", "vb.net", "c", "c++" };

        IList<String> lst = Array.AsReadOnly(arr);

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

        try  {
            lst[1] = "abc";
        }
        catch (NotSupportedException ex)  {
            Console.WriteLine("{0} - {1}", ex.GetType(), ex.Message );
        }
   }
}



/*
run:

c#
vb.net
c
c++
System.NotSupportedException - Collection is read-only.

*/

 



answered Dec 3, 2020 by avibootz
...