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

What is the difference between the ranges "^4" and "^4.."?

I was trying to get the substring from a string I am using in my program as follows:

mystring.Substring(mystring.Length - 4)

The Visual Studio IntelliSense recommended I use index and range operators as follows:

mystring[^4..]

I glanced through the documentation here and it seems like using just mystring[^4] would work just fine. Why does the IntelliSense recommend to use the extra .. in there, are there any benefits from adding it?

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

>Solution :

^4 is an index, representing a single index number which just so happens to be 4 away from the end of the array. This is essentially the same as doing mystring[0], just dynamically figuring out the number based on the length.

^4.. is a range, which means everything between (and including) the 4th-to-last index and the end of the array.

var input = "abcdefghijk";
Console.WriteLine(input[^4]);
Console.WriteLine(input[^4..]);

This prints

h
hijk
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