Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array from nullable type to non-nullable of same type?

I would like to convert a Nullable(Of Byte)() array (a.k.a. byte?[]) to a non-nullable array of the same type, that is, from byte?[] to byte[].

I'm looking for the simpler, easier, faster generic solution, in C# or VB.NET. I've found this generic function to convert between nullable types but I can't find a way to adapt the conversion logic to convert from a nullable type to a non-nullable type.

This is a code example for which I feel the need to perform that kind of conversion:

byte?[] data = {1, 0, 18, 22, 255};
string hex = BitConverter.ToString(data).Replace("-", ", ");
like image 995
ElektroStudios Avatar asked Sep 03 '16 19:09

ElektroStudios


2 Answers

To convert an array of one type to an array of another type, use the Array.ConvertAll method:

byte?[] data = { 1, 0, 18, 22, 255 };
byte[] result = Array.ConvertAll(data, x => x ?? 0);

This is simpler, easier, and faster than using LINQ.

like image 148
Michael Liu Avatar answered Nov 08 '22 08:11

Michael Liu


This method has to make an assumption of how to handle a null value. For this solution it is mapped to default(byte) = 0 in order to have input and output to be of the same length.

byte?[] data = {1, 0, 18, 22, 255, null};
var byteArray = data.Select(
                 b => b ?? default(byte)).ToArray();
like image 6
Ralf Bönning Avatar answered Nov 08 '22 09:11

Ralf Bönning