Converting a Object[] array to an string[] array in c#?

arrays, c#

Solution

If you have a method to convert an `object` to a `string` (or `int`) with null check, then you can use the Array.ConvertAll<TInput, TOutput> Method to convert an `object[]` to a `string[]` (or `int[]`):

object[] input = ...;
string[] result = Array.ConvertAll<object, string>(input, ConvertObjectToString);
string ConvertObjectToString(object obj)
{
    return obj?.ToString() ?? string.Empty;
}

If you want to skip items in the `object[]` array when converting to a `string[]`, a more convenient approach might be using the extension methods of the Enumerable Class:

object[] input = ...;
string[] result = input.Where(x => x != null)
                       .Select(x => x.ToString())
                       .ToArray();

Problem

I have many ways to do it but still want to know is there any offical API to convert object[] to string[] With null checked? Thanks

Original source