Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Intermediate C# System.Object Object.Equals

Richard Külling
Richard Külling
9,465 Points

is this a foreach convention?

foreach usage

Steven Parker
Steven Parker
231,268 Points

Please show the code you are asking about, and elaborate a bit more about what aspect of it you are wondering is a "convention".

Richard Külling
Richard Külling
9,465 Points

Oops, sorry, the code I had attached has gone missing it seems!

Jeremy coded the loop like this: foreach(var pathLocation in _path)

But why not use the name and the type of the values that are looped for, and that are within path, like so: foreach (MapLocation mapLocation in _path)

Why does he use var, and why does he give the values the new name pathLocation. How does the compiler even know if pathLocation is the amount of arrays, points, MapLocations or else? Doesn't he get confused whether he has to use the amount of arrays of MapLocations or amounts of MapLocations?

1 Answer

Steven Parker
Steven Parker
231,268 Points

Using "var" just causes the type to be determined by the contents of the iterable. The compiler knows that "_path" is an array of MapLocations. You can use "MapLocation" if you prefer and the code will do exactly the same thing.

The name is of no importance to the system — you could name it "George" if you like. But I might guess that "pathLocation" is a shorthand for "a MapLocation that is part of the path".

There is no confusion because as the "foreach" runs, a "pathLocation" will be only one "MapLocation" from the "_path" array.