Listing with random bytes

I am trying to fill a buffer with random bytes. A buffer is defined as a list of bytes. This is what I want to keep as it is. Here is the definition:

namespace NameofProject { public partial class Form1 : Form { List<byte> buff = new List<byte>(); } } 

And my first attempt

 public static void RandomFillBuffer() { Random rnd = new Random(); rnd.NextBytes(buff); } 

However, this gives such an error for buff: An object reference is required for a non-static field, method or property 'Form1.buff'

Then I just deleted the word โ€œstaticโ€ (I'm not sure it's true) and it becomes โ€œpublic void RandomFillBuffer ()โ€, but this time I get this error for buff: Argument 1: cannot be converted from 'System.Collections. Generic.List 'in' byte [] '

I would be grateful for any help in resolving any of the two errors, if they make sense.

+5
source share
3 answers

You get this problem because NextBytes() expects an array, but you are trying to pass List<> . One way to solve it is to change your List<> to an array:

 byte[] buff = new byte[someSize]; 

You will need to figure out what someSize should be (it is up to you). You cannot fill in something without size. Otherwise, how will he know when it will be done?

+5
source

The problem you are facing is that NextBytes populates the array [], not the list. You need to define an array with its size index

  // Put random bytes into this array. byte[] array = new byte[8]; // Fill array with random bytes. Random random = new Random(); random.NextBytes(array); 
+2
source

First you tried to make your method static (this means that this method is not associated with any instance of the object, but instead with a class of objects) and tried to refer to a non-stationary member from it (your buff not static and therefore associated with a specific instance specific Form in your case). Secondly: you tried to use Random.NextBytes(System.Byte[]) , but provided System.Collections.Generics.List<System.Byte> as an argument.

The code below should work for you (this code assumes that at least buff already has some data and therefore has a positive length):

 var generator = new Random(); var array = new Byte[buff.Count]; // create a local array of the same size as your list generator.NextBytes(array); // fill the array with random bytes buff = array.ToList(); // copy array to a new list and let field "buff" reference this freshly created list 

Please note that this code is not optimal, as it copies the array. But he does what you want, I think.

+1
source

Source: https://habr.com/ru/post/1271367/


All Articles