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 trialBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsThis syntax seems strange
I noticed some new syntax in this video:
while ((line = reader.ReadLine()) != null)
{
string[] values = line.Split(',');
soccerResults.Add(values);
}
It seems like we're simultaneously assigning a variable and also checking a boolean condition. Is this a C# only thing or is it possible to do this in other languages? Is there a word for this?
2 Answers
Jennifer Nordell
Treehouse TeacherHi there, Brendan Whiting ! To be honest, I'm not sure if this has a name or not, but this syntax is found in the MSDN ReadLine() documentation.
That being said, I know you have some points in PHP, and the same sort of thing can also be done there.
Let's say I have this (in PHP):
if($student = "Jennifer")
Now normally, we want the double equals to make a comparison, but this is also valid syntax. And what it's saying is "if the assignment to the $student variable contains a truthy value, evaluate this as true". This sort of thing helps prevent things like null, empty strings etc.
The same sort of thing is happening here. We're making an assignment inside the conditional and then asking if that assignment was null. Luckily, ReadLine()
does almost exactly what we would expect by the name. It reads a line of text and returns a string. If it's out of lines, it returns a null
. This code says, "while there are still lines left to be read, read the next line. When there are no more lines, stop."
Hope this helps!
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsVery cool. I will think on this some more.
benovarghese
2,059 Pointswould it assign a -1 to line when it reaches end of file or does -1 only apply if we were using peek()?
Ole Vølund Skov Mortensen
27,842 PointsOle Vølund Skov Mortensen
27,842 PointsVisual studio 2019 throw a error say: Error CS860 Converting null literal or possible null value to non-nullable type. It refers to this line: reader.ReadLine()