C# C# Streams and Data Processing Parsing Data Reading Line By Line

Brendan Whiting
Brendan Whiting
Front End Web Development Techdegree Graduate 84,615 Points

This syntax seems strange

I noticed some new syntax in this video:

while ((line = reader.ReadLine()) != null)
    string[] values = line.Split(',');


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
Jennifer Nordell
Treehouse Staff

Hi 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! :sparkles:

would it assign a -1 to line when it reaches end of file or does -1 only apply if we were using peek()?