Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading