ElektroStudios ElektroStudios - 11 months ago 65
Vb.net Question

Convert nullable type to non-nullable of same type?

I would like to convert a

Nullable(Of Byte)()
Array (a.k.a
) to a non-nullable of the same type Array, that is, from

I'm looking for the simpler, easiest, faster, generic solution, in C# or VB.NET. I've found this generic function to convert between nullable types but I cant find the way to adpat the conversion logic to convert from nullable type to 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("-", ", ");

Answer Source

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();