1

I need to be able to set the objects in the array, but I don't want to be able to change the state of any of the individual objects.

3 Answers 3

3

You can't, I'm afraid. There's no equivalent of the flexible "const" from C++ in C#.

If it's your own type, you could try to make it immutable (like string) to start with though. That would be pretty effective against changes :)

Note that although your question asks for a writable array, there's actually no other kind - you can't create an array which is read-only when initially populated... you have to use some other approach (e.g. creating a ReadOnlyCollection<T> wrapping another collection which is only known to the wrapper). I know this isn't a problem in your particular case, but I just thought I'd point it out. If you make the variable referring to the array readonly, that only prevents other code from setting the value of the variable to a reference to another array - it doesn't prevent changes within the array itself.

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

Comments

0

Well, you can declare a private variable and then declare a property referencing the variable with only getter defined, that sort of makes it read only.

Example:

private int[] myArray =new int[5];
public int[] MyArray
{
  get { return MyArray; }
}

4 Comments

I don't believe that addresses the point the OP was trying to achieve - e.g. having an array of type StringBuilder[] but preventing the contents of each StringBuilder from changing.
@Jon: hmm..reading his wording again, i guess you are right but i guess the OP should make the decision on what the point he was trying to achieve and down vote my answer and not you..haha...
I'd actually already undone my downvote, but it seems to be pretty clear that your answer doesn't address the OP's concern.
@Jon: I agree, your answer i think covers what he's asking for.
0

I would look into using some form of Immutable collection as a better design concept.

Options include returning as IEnumerable, IEnumerable using yield[1], ReadOnlyCollection... See link down below for better explanation.

[1]

public IEnumerable<string> Hosts 
      { 
            get     
             {     
                 foreach (var host in _hosts)
                 {    
                     yield return host;
                 }    
             }
     }

See http://geekswithblogs.net/BlackRabbitCoder/archive/2010/11/04/c.net-fundamentals-returning-an-immutable-collection.aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.