convert string[] to int?[]

c#

Solution

Well, the two aspects are:

- How do you convert an array from one type to another?

- How do you convert a string to a nullable int?

The first is simple - you can use `Array.ConvertAll`, passing in an `Converter` delegate. There's the LINQ way as well (`x.Select(...).ToArray()`), but that's slightly less efficient if you know you've got an array to start with and you want an array out of the other end 1.

The `string` to `int?` is probably best done in a method. You can do it in an anonymous function, but in this particular case I'd use a separate method. I rarely like to have to declare variables in an anonymous function.

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

To answer the comment, yes you need the cast 2.

or without the conditional:

public static int? TryParseInt32(string text)
{
    int value;
    if (int.TryParse(text, out value))
    {
        return value;
    }
    else
    {
        return null;
    }
}

Put them together like this:

string[] x = {"15", "10", "hello", "5" };        
int?[] y = Array.ConvertAll(x, TryParseInt32);

1 `Array.ConvertAll` is more efficient than `x.Select().ToArray()` because it has more information. It can create the final array immediately - no resizing is ever required. Calling `Enumerable.ToArray()` (with the result of `Select()`) doesn't have the same information, so it effectively has to add the results to a `List<T>` (potentially resizing several times along the way) and then usually resize at the end as well. (It doesn't actually use `List<T>` but the concepts are the same.) It's definitely worth knowing about the Select/ToArray solution, but I don't think it's actually any more readable than `ConvertAll` in this case, so you might as well use the more efficient form.

2 The reason you need the cast in the conditional is because the compiler doesn't know what type of "null" you really mean - but it knows it can't convert from `null` to an `int`. The type of the conditional expression has to be either the type of the second operand or the type of the third operand, and the other one has to be implicitly convertibly. By forcing the third operand to be of type `int?` here everything is fine - because you can implicitly convert from `int` to `int?`. Note that the compiler doesn't take the way you're using the expression to try to work out the type. Another alternative is to use `new int?()` instead of `null`.

Problem

how to convert a string array to nullable integer array.

Original source