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
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.
Comments
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
StringBuilder[] but preventing the contents of each StringBuilder from changing.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;
}
}
}