3

Say I have a property like this:

public int[] MyProperty
{
    get;
    set;
}

The calling code is free to change the values of the array, but also to replace the array itself. This can easily be prevented by hiding the setter, like so:

public int[] MyProperty
{
    get;
    private set;
}

This allows the calling code to change the values, but it can't change the array to a different one, or change the size.

This pattern works with multidimensional arrays, but not jagged arrays. If I have this:

public int[][] MyProperty
{
    get;
    private set;
}

The main array can't be modified, but the child arrays can. What if I want to make the child arrays readonly, so that the calling code can change the elements, but not the arrays?

How can I make only the elements of jagged arrays modifiable? This includes 3D and higher.

1

1 Answer 1

3

You should use a ReadOnlyCollection<int[]>.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 very nice, could you elaborate just slightly to use it in a code example
Cool. Is there a way to solve the problem with jagged arrays?
@KendallFrey: No, there isn't.
Another question: I don't suppose there is anything wrong with ReadOnlyCollection<Collection<int>>? It seems more uniform, that's all.
@KendallFrey: That would actually be better. Note, though, that clients will be able to Add() and Remove() from the inner collections.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.