0

I'm trying to make a queue of orders for my clients. But the last added value replace all the values ​​in the queue.

Debbuging the code i've see that when a value is enqueued it overrides all the other values in the queue.

class Program
{

    static void Main(string[] args)
    {
        Console.WriteLine("Starting...");
        byte[] dataInit = new byte[] { 0x00 };
        Client clientTest = new Client();


        for (int i = 0; i <= 5; i++)
        {
            dataInit[0]++;
            Console.WriteLine("Adding Order -  i = {0}; Order: {1}.", i, BitConverter.ToString(dataInit));
            clientTest.AddOrder(dataInit);
            Console.WriteLine("Peeking Order - i = {0}; Order: {1}", i, BitConverter.ToString(clientTest.PeekOrder()));
        }

        for (int i = 0; i <= 5; i++)
        {
            Console.WriteLine("Removing order - i = {0}; Order: {1}.", i, BitConverter.ToString(clientTest.RemoveOrder()));
        }

        Console.WriteLine("Press Any Key...");
        Console.Read();

    }

    class ClientOrder
    {
        public byte[] Order;


        public ClientOrder(byte[] data)
        {
            Order = data;
        }


    }

    class Client
    {
        public Queue<ClientOrder> ClientOrders = new Queue<ClientOrder>();

        public void AddOrder(byte[] orderToAdd)
        {
            ClientOrders.Enqueue(new ClientOrder(orderToAdd));
        }

        public byte[] RemoveOrder()
        {

            ClientOrder toReturn = ClientOrders.Dequeue();
            return toReturn.Order;
        }

        public byte[] PeekOrder()
        {
            ClientOrder toReturn = ClientOrders.Peek();
            return toReturn.Order;
        }
    }
}

i've expected that the queue was in order [0-6]. but the actual output is {06,06,06,06,06,06} (The last value added).

1 Answers1

2

You are actually sharing the same reference to byte[] and then with every Enqueue you actually replace all the elements in the queue as they all reference the same array. You should make a copy when creating ClientOrder. The easy way is using Linq, but there are also other possibilities.

public ClientOrder(byte[] data)
{
    Order = data.ToArray();
}

or other way around as Jeff said

Johnny
  • 8,939
  • 2
  • 28
  • 33
  • 1
    Or to state it another way, every `ClientOrder` you create in `Client.AddOrder` is using the same `byte[]` so as you run `dataInit[0]++` every other `ClientOrder` object's `byte[] Order` will also change. – Jeff B Feb 14 '19 at 20:44