How to Work with Readonly keyword in Array

In this article I am going to explain that how to create Read only Method in Array.
  • 2892

Keyword Readonly in C# is a modifier and it is used with fields. You can use readonly at run time and it is also used to hold some value. Another feature of readonly keyword is that once a read only value has been assigned to it don't to assign again until the program is restarted.

Here I am explaining how to work with readonly keyword in C#

When the variable is initialized in the declaration 

public readonly datatype name_of_variable = value;
public readonly int a = 10;

using System.Collections.ObjectModel;

 

namespace demo_array

{

    class Program

    {

      

        static void Main(string[] args)

        {

            int[] zArray = { 1, 2, 3, 4 };

            zArray[1] = 10;

 

            ReadOnlyCollection<int> roArray = Array.AsReadOnly(zArray);

            foreach (int number in roArray)

            {

                Console.WriteLine(number);

            }

 

           // roArray[1] = 2; // compile error

            Console.ReadKey();         

        }

    }

}


Output

readonly_method.gif

Ask Your Question 

 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.