Search code examples
c#arraysstringindexoutofrangeexception

Get string from array or set default value in a one liner


So we have ?? to parse its right-hand value for when the left hand is null. What is the equivalent for a string[].

For example

string value = "One - Two"
string firstValue = value.Split('-')[0] ?? string.Empty;
string secondValue = value.Split('-')[1] ?? string.Empty;

Above example would still crash if we would try to get a third index or if string value = "One". Because it is not null but IndexOutOfRangeException is thrown.

https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception

So what is a one-line solution to tackle the above problem? I'd like to avoid the try-catch scenario because this gives ugly code.

I want to get value out of a string[] with a string.Empty as a backup value so my string is never null.


Solution

  • Well, you can try Linq:

    using System.Linq;
    
    ...
    
    string thirdValue = value.Split('-').ElementAtOrDefault(2) ?? string.Empty;
    

    However, your code has a drawback: you constantly Split the same string. I suggest extracting value.Split('-'):

    string value = "One - Two"
    var items = value.Split('-');
    
    string firstValue = items.ElementAtOrDefault(0) ?? string.Empty;
    string secondValue = items.ElementAtOrDefault(1) ?? string.Empty;