Search code examples
c#arrayscopybyte

How to copy from byte[] to new byte[] with some changed element item?


I have byte[] like this, the length of byte[] is 16, and I want to change some value of an item and add this to a new byte[]. For example, the value of byte[7] is 13, I want to change this value with a new value. After that, add into a new byte, the value of byte[7] will be changed plus one more unit.

enter image description here

enter image description here


Solution

  • You should perform the operations the other way round. First copy then change the value in the copied data. This way the original will stay unchanged.

    Efficient:

    var original = new byte[]{1,2,3};
    var result = new byte[original.Length];
    
    Array.Copy(original, result, original.Length); //first make a copy
    result[2] = 42; //then set your new value
    //result is now [1, 2, 42]
    

    Simple with LINQ:

    //do not forget using System.Linq;
    var original = new byte[]{1,2,3};
    
    var result = original.ToArray(); //first copy
    result[2] = 42; //then set your new value
    //result is now [1, 2, 42]
    

    For small data there will be no difference in performance. For large arrays the direct copy should perform a bit better. See this answer for further alternatives regarding the copy part.