Search code examples
c#.net-5indices

C# improper result of index range expression


I'm slightly confused with index range operator: I expected that the expression myString[..0] should be equvalent to myString[0..0], then myString.Substring(0, 1) or myString[0].ToString(), and in case of code below:

string myString = " abc";
string resultString = myString[..0];

the resultString value should be a single space " ". Unfortunately, I got String.Empty :(

Does anybody know why and can explain me, why I'm wrong?

The Microsoft docs doesn't describe similar cases (or I can't find them).


Solution

  • the resultString value should be a single space " "

    No, it shouldn't.

    The end of a range is exclusive, not inclusive. So for example, x[0..x.Length] will always return the whole string.

    In your case, you're saying "everything before index 0" which is obviously "the empty string".

    This is documented in (aside from other places) the documentation for Range.End:

    Gets an Index that represents the exclusive end index of the range.