Think of the following code:
static int Main() {
byte[] data = File.ReadAllBytes("anyfile");
SomeMethod(data);
...
}
static void SomeMethod(byte[] data) {
data[0] = anybytevalue; // this line should not be possible!!!
byte b = data[0]; // only reading should be allowed
...
}
Is there a way of readonly passing the byte[] in C#? Copying isn’t a solution. I would not like to waste memory (because the file might get very big). Please keep performance in mind!
You can pass a
ReadOnlyCollection<byte>, like this:However, it would be better to pass a
Stream, like this:This way, you won’t read the entire file into memory at all.