1

In the following method, how can I prevent the contents of my array from being modified accidentally or otherwise?

Can it be done without changing the array to another type, such as a list?

    public static int LinearSearch(int[] myArray, int target)
    {
        int idx = -1;
        for (int i = 0; i < myArray.Length; i++)
        {
            if (myArray[i] == target) { idx = i; break; }
        }
        return idx;
    }
uccstudent
  • 11
  • 2

1 Answers1

1

Use the ImmutableArray<T> class.

Provides methods for creating an array that is immutable; meaning it cannot be changed once it is created.

For instance:

ImmutableArray<int> array = ImmutableArray.Create(1, 2, 3);

You can also try the ReadOnlyCollection<T> class, that doesn't include a .Add method.

vinibrsl
  • 6,563
  • 4
  • 31
  • 44
  • This solution puts a burden on the user of OPs method to only pass ImmutableArray references. – nicomp Sep 25 '19 at 12:38