Can we use negative index in c#. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can we use negative index in c#.

string x="hello"; Console.Writeline(x[-1]); It give me error but we can do in python does c# is support this.

23rd May 2019, 12:37 PM
Maninder $ingh
Maninder $ingh - avatar
2 Answers
+ 9
Maninder $ingh Negative values are not permitted as index values by the C# compiler, which is more strict than C/C++ compilers which leave it to the programmer to not supply negative index values. source: https://social.msdn.microsoft.com/Forums/en-US/831c1abd-eac5-44e2-b4c8-229523f51d24/how-do-i-set-a-negative-number-to-index-of-array-in-c-?forum=csharpgeneral I hope I was helpful
23rd May 2019, 12:55 PM
Alessio Benvenuti
Alessio Benvenuti - avatar
+ 3
Negative index in Python does something different: it is a shortcut for thatlist[len(thatlist)-1]. In C it is literally -1, so the element 'left side' of element 0 (which is normally 'somewhere in memory').
23rd May 2019, 1:00 PM
HonFu
HonFu - avatar