Question

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!

Was it helpful?

Solution

You can pass a ReadOnlyCollection<byte>, like this:

static int Main() {
     byte[] data = File.ReadAllBytes("anyfile");
     SomeMethod(new ReadOnlyCollection<byte>(data));
     ...
}
static void SomeMethod(ReadOnlyCollection<byte> data) {
     byte b = data[0];       // only reading is allowed
     ...
}

However, it would be better to pass a Stream, like this:
This way, you won't read the entire file into memory at all.

static int Main() {
     Stream file = File.OpenRead("anyfile");
     SomeMethod(file);
     ...
}
static void SomeMethod(Stream data) {
     byte b = data.ReadByte();       // only reading is allowed
     ...
}

OTHER TIPS

I think this might be what you're looking for.

Compile the code below and you will get this compile error: Property or indexer 'Stack2.MyReadOnlyBytes.this[int]' cannot be assigned to -- it is read only

public class MyReadOnlyBytes
{
   private byte[] myData;

   public MyReadOnlyBytes(byte[] data)
   {
      myData = data;
   }

   public byte this[int i]
   {
      get
      {
         return myData[i];
      }
   }
}

class Program
{
   static void Main(string[] args)
   {
      var b = File.ReadAllBytes(@"C:\Windows\explorer.exe");
      var myb = new MyReadOnlyBytes(b);

      Test(myb);

      Console.ReadLine();
   }

   private static void Test(MyReadOnlyBytes myb)
   {
      Console.WriteLine(myb[0]);
      myb[0] = myb[1];
      Console.WriteLine(myb[0]);
   }
}

I would recommend you using the highest possible object in the hierarchy that does the job. In your case this would be IEnumerable<byte>:

static int Main() 
{
     byte[] data = File.ReadAllBytes("anyfile");
     SomeMethod(data);
}

static void SomeMethod(IEnumerable<byte> data)
{
    byte b = data.ElementAt(0); 
    // Notice that the ElementAt extension method is sufficiently intelligent
    // to use the indexer in this case instead of creating an enumerator
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top