Search code examples
c#arraysbyteenumerable

how to create array with n number of bytes?


How to create byte[] digits; with n number of bytes?

I know I can do Enumerable.Range(1, n).ToArray(); but this creates an int[]. Is there a way to create a byte[]?

My priority is a fast performance. Keeping this in mind, is there a faster way (with slightly more code) that can create this?


Solution

  • What's wrong with just creating a byte array instance?

    byte[] digits = new byte[n];
    

    And if you want to initialize with values from 1 to n, then I think:

    for(int i = 1; i <= n; i++)
       digits[i-1] = (byte)i; // index is 0-based
    

    Will also get you the desired result as fast as possible. Of course, where n < 256!