Is there any way of creating a read only reference to an array? My
class includes a private array of bytes with a Property to access it.
However, I do not want users to use the returned reference to modify
the array; modifications are only allowed through the property, which
includes error checking. I have been trying to use Array.AsReadOnly()
to return a read only reference, but with very little success:
public class Foo {
private byte[] m_bytes;
public Foo() { m_bytes = new byte[] { 0x00, 0x01, 0x02 }; }
public byte[] Bytes {
get { return Array.AsReadOnly(m_bytes); }
set { /* error checking omitted */ m_bytes = value; }
}
}
This gave a compile time error:
Cannot implicitly convert type
'System.Collections.ObjectModel.ReadOnlyCollection <byte>' to 'byte[]'
Trying an explicit conversion didn't work either, nor did
AsReadOnly<byte>() with or without explicit conversion.
My next effort looked like:
get {
IList<bytetemp = Array.AsReadOnly<byte>(m_bytes);
return (byte[])temp;
}
This compiled fine but threw a runtime error:
Unable to cast object of type
'System.Collections.ObjectModel.ReadOnlyCollection `1[System.Byte]' to
type 'System.Byte[]'.
Changing IList to List just gave a compile time error.
For the moment I am creating a cloned copy of the arrray and returning
that, but it is not an ideal solution as the users can amend the
cloned copy and get unexpected results when my class uses the
unchanged original. Is there anything better I could do to get a read
only array reference?
Thanks,
rossum