Assigning values to a public byte array in one line C#

arrays, c#, public

Solution

Your first example is fine but it may only be used in a declaration. The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.

byte[] foo = { 0x32, 0x00, 0x1E, 0x00 };

Alternatively you can also d this

byte[] foo = new byte[4];
foo[0] = 0x32;
foo[1] = 0x00;
foo[2] = 0x1E;
foo[3] = 0x00;

as stated above that the syntax that you are trying to use can only be used in a declaration. so try like this.

public byte[] SetSpeed;
private void trackBar1_Scroll(object sender, EventArgs e)
{
    if (trackBar1.Value == 0)
    {
        try
        {
            stop = true;
            UpdateSThread.Abort();
            Thread.Sleep(350);
        }
        catch { }

        //note it will always create a new array
        SetSpeed = new byte[]{0x00,0x00,0x00,0x00}; 
        WriteMem(GetPlayer() + STATUS_OFFSET, SetSpeed);
        label1.Text = "Normal";              
    }
}

Problem

I am working with a public byte array and would like to assign values, like I assign arrays inside a method, i.e ``` byte[] foo = {0x32, 0x00, 0x1E, 0x00}; ``` but when I define the values I am forced to do ``` foo[0] = 0x32; foo[1] = 0x00; foo[2] = 0x1E; foo[3] = 0x00; ``` If I use the first example VS gives an error "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" If it helps any, the array is always 4 bytes. my code ``` public byte[] SetSpeed = new byte[4]; private void trackBar1_Scroll(object sender, EventArgs e) { if (trackBar1.Value == 0) { try { stop = true; UpdateSThread.Abort(); Thread.Sleep(350); } catch { } SetSpeed = {0x00,0x00,0x00,0x00}; WriteMem(GetPlayer() + STATUS_OFFSET, SetSpeed); label1.Text = "Normal"; } } ```

Original source