Recently, I was working on some graphics manipulation, and I needed to create and initialize an array with all its elements set to 1.

There are several ways to do this:

LINQ

Our old friend LINQ can always be relied on to have something in the toolbox. In this case, we can use the Repeat() method of the Enumerable.

var byteArray = Enumerable.Repeat(1, 50).ToArray();

For Loop

Another way would be to declare an array and then fill it with a for loop:

byte[] byteArray = new byte[100];

for (var i = 0; i < 50; i++)
  byteArray[0] = 1;

Array Fill

The Array type has a Fill() method that you can use for this purpose.

byte[] byteArray = new byte[100];

Array.Fill(byteArray, (byte)1);

Span Fill

You can also leverage the Span for this purpose, as it has a Fill() method.

byte[] byteArray = new byte[100];

var span = new Span<byte>(byteArray);
span.Fill(1);

BONUS

You can also quickly reset the array to all zeros using the Array.Clear() method as follows:

Array.Clear(byteArray);

Happy hacking!