I have a byte[] array of one size, and I would like to truncate it into a smaller array?
I just want to chop the end off.
By the way, Array.Resize method takes much more time to complete. In my simple case, I just needed to resize array of bytes (~8000 items to ~20 items):
You can't truncate an array in C#. They are fixed in length.
If you want a data structure that you can truncate and acts like an array, you should use List<T>
. You can use the List<T>.RemoveRange method to achieve this.
You could use Array.Resize, but all this really does is make a truncated copy of the original array and then replaces the original array with the new one.
Arrays are fixed-size in C# (.NET).
You'll have to copy the contents to a new one.
byte[] sourceArray = ...
byte[] truncArray = new byte[10];
Array.Copy(sourceArray , truncArray , truncArray.Length);
private static void Truncate() {
byte[] longArray = new byte[] {1,2,3,4,5,6,7,8,9,10};
Array.Resize(ref longArray, 5);//longArray = {1,2,3,4,5}
//if you like linq
byte[] shortArray = longArray.Take(5).ToArray();
}
I usually create an extension method:
public static byte[] SubByteArray(this byte[] byteArray, int len)
{
byte[] tmp = new byte[len];
Array.Copy(byteArray, tmp, len);
return tmp;
}
Which can be called on the byte array easily like this:
buffer.SubByteArray(len)