ElektroStudios ElektroStudios - 1 year ago 99
Vb.net Question

Convert array from 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 array of the same type, that is, from

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download