Converting byte[] into byte?[]

  • Thread starter Thread starter Narshe
  • Start date Start date
N

Narshe

How can I convert a byte[] into a byte?[]?

You can assign a byte to a byte?, but you obviously can't do that with
an array. The way I'm currently doing it is a for loop that just copies
the data from a byte[] to the byte?[].

There must be an easier/better way.
 
Narshe,

There is an easier way. In .NET 2.0 (which you must be using because
you are using the nullable type), you can do:

nullBytes = Array.ConvertAll<byte, byte?>(bytes,
delegate(byte b)
{
return b;
});

This works because there is an implicit cast between byte and byte?

Hope this helps.
 
Narshe said:
How can I convert a byte[] into a byte?[]?

You can assign a byte to a byte?, but you obviously can't do that with
an array. The way I'm currently doing it is a for loop that just copies
the data from a byte[] to the byte?[].

There must be an easier/better way.

I suspect it's not something which is needed particularly often, so I
doubt that there *is* a better way. You could probably write a method
which does it in a generic way, so you'd only have to call that method
whatever type you had.

Even if the framework provided some way itself, it would just be doing
the for loop internally...

Jon
 
Even if the framework provided some way itself, it would just be doing
the for loop internally...

Jon
Of course, but it is preferable to use 'system' methods,
whenever possible, than to build your own.
Roger
 
but also beware of the implication.

in this case, using ConvertAll, for each iteration, you are making a
delegate call which is significantly slower than a direct call, and because
it can't be inlined, an extra stackframe as well, for something as simple as
convert from byte to byte? This overhead may or may not be an issue.

generally speaking though, I too prefer using the provided generics/delegate
based collection methods. it hides the loop and leaves only the logic and
results in cleaner code imo.
 
Daniel,

You know they sped up delegate invocation for .NET 2.0, right?

I would say if this is an issue for you, you are going to hate LINQ =)
(I know you won't, you stated your preference in your post, but I couldn't
help but think this when you responded).
 
Back
Top