Bustedspoke Bustedspoke - 1 year ago 70
C# Question

What is the meaning of "-1" in the following C# code?

Hey guys I'm just starting to learn C# and I was wondering what the "-1" in the for loop meant?

string[] fruit = { "Apples", "Oranges", "Grapes" };
for (int i = fruit.Length - 1; i >= 0; i--)
// Code Here

I was trying to figure out how to go backwards in an array and I was able to do it, but I just want to know how the "-1" works in the for loop. Why is it necessary?

Answer Source

Arrays in C# are 0-indexed, meaning they begin at element [0]. Thus, the largest accessible index is Length-1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download