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 trialCam Newton
1,737 PointsRegarding Question 4 in quiz?
Hi Nick!
I didn't know that you could assign a variable in an if statement's clause. Is that an advanced technique?
I was expecting the answer to be more like "The first line would not compile and the second line would return true/false".
3 Answers
Nick Pettit
Treehouse TeacherIn C#, assigning a boolean inside a conditional statement is generally not advised, because it will always be constant. In other words, if you assign a boolean inside the conditional statement, the if statement will always execute. When compiling, typically it will return a warning. However, it should still compile and run. I wrote a quick demonstration of this in Workspaces. Here's the link to the Workspaces snapshot, along with a screenshot below of the code and what it looks like when it runs in a console window.
Cindy Lea
Courses Plus Student 6,497 PointsVariables dont all have to be defined in the beginning. The ones in the beginning of the code are the ones that are needed right away. In the old days they were more stricter about the variable s being on top of the programming code. Later on when you are doing functions in your class, you will see that variables might be defined within a function so variables are defined when they need them.
Cam Newton
1,737 PointsSorry, Cindy, upon reading your answer it's made me realise my statement wasn't at all clear (as I'm not so familiar with the terminology yet). What I was trying to say was that I thought this would return an error, because it's assignment not comparison:
if (myVariable = true) {
// code here
}
Does that make more sense? How would I have communicated that correctly? Thank you for your reply.
Cam Newton
1,737 PointsCam Newton
1,737 PointsThanks for the detailed explanation and example, Nick. That all makes sense now, except that it seems like an odd practice when it's no longer conditional!