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.
Asked
Active
Viewed 61 times
0

Saeed Zhiany
- 2,051
- 9
- 30
- 41

Headshot
- 423
- 1
- 6
- 22
-
Call Array.Copy and then change the bytes to be changed in a next step? – Ralf Jun 02 '23 at 10:34
-
So, not look like this , copy to another byte[] but some changed element in array @Renat – Headshot Jun 02 '23 at 10:40
-
@Ralf . Are you draff detail with it. – Headshot Jun 02 '23 at 10:41
-
2Why can't you copy the array and then change the value? – shingo Jun 02 '23 at 10:56
1 Answers
1
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.

Isolin
- 845
- 7
- 20