Reputation: 1
I have code like this to convert nullable arrays to ordinary arrays
object myCoolConvertion(object value)
{
if (value is int?[])
return Array.ConvertAll((int? [])value, x => x ?? default(int));
if (value is double?[])
return Array.ConvertAll((double?[])value, x => x ?? default(double));
if (value is float?[])
return Array.ConvertAll((float?[])value, x => x ?? default(float));
return value;
}
Is it possible to write universal code for any types like
if (value is T?[])
return Array.ConvertAll((T? [])value, x => x ?? default(int));
Upvotes: 0
Views: 217
Reputation: 22073
I'd rather filter the null
object's out. Because default structs are not useful and can not be distinguished between a real objects.
I use the IEnumerable.OfType() for this.
using System;
using System.Linq;
public class Program
{
public static T[] ConvertWithout<T>(T?[] array) where T : struct =>
array.OfType<T>().ToArray();
public struct TestStruct
{
public string Name {get;set;}
}
public static void Main()
{
var testArray = new TestStruct?[]
{
new TestStruct { Name = "Peter"},
null,
new TestStruct{Name="John"}
};
var result = ConvertWithout(testArray);
foreach(var person in result)
Console.WriteLine(person.Name);
}
}
results:
Peter
John
Upvotes: 2
Reputation: 22819
Just a side note for Iridium's answer:
The Nullable<T>
has a method called GetValueOrDefault
, which can make your code a bit more concise:
T[] Convert<T>(T?[] array) where T : struct
=> Array.ConvertAll(array, t => t.GetValueOrDefault());
Upvotes: 2
Reputation: 23731
You can do this with a generic method, e.g.:
T[] Convert<T>(T?[] array) where T : struct
{
return Array.ConvertAll(array, t => t ?? default(T));
}
Upvotes: 4