MrDysprosium MrDysprosium - 3 months ago 14
C# Question

Using Take() to grab bytes out of a byte array, having trouble converting back to byte[] after the Take()

byte[] result = memStream.ToArray();
memStream.Close();
byte[] temp = result.Take(255);
var str = System.Text.Encoding.Default.GetString(temp);


The above fails on the
result.Take(255);
line. It says I can't convert
IEnumerable
to
byte[]
, and asks if I'm missing a cast.

I'm new to C#, not exactly sure what to do.

Answer

Take() returns an enumerator object that executes when you enumerate it:

enter image description here

That's not an array, so you can't assign it to a reference to a byte array. However, with LINQ, you can take any sequence and convert it to an array of the appropriate type by calling its ToArray() method:

byte[] temp = result.Take(255).ToArray();

ToArray() enumerates the result from Take(255), puts the results in a new array, and returns the array.

It's a little confusing because you can enumerate an array just like you can enumerate the thing you get from Take(255) -- but you can enumerate a lot of things. That's just one behavior they have in common, but they're actually very different objects.

You could assign either one to IEnumerable<byte>:

IEnumerable<byte> a = result.Take(255);
IEnumerable<byte> b = result.Take(255).ToArray();

...because that's one thing they really have in common.

Comments