we had a programing lesson today. Very easy exercise in console. I wrote a loop to load from console char by char by getchar() with assignment, all of these in loop term.
char c;
while((c = getchar()) != '\n'){
...
Someone says, that this isn’t safe to use, others says, that in C/C++ I can do this, but not in C#.
I tried this
string s;
if((s = Console.ReadLine()) != ""){
...
But this also works, so I don’t understand why this is unsafe. Or isn’t it?
Edit:\ I also read this Why would you use an assignment in a condition? but this isn’t answer to my question at all.
The main operation in your sample is
!=which is not an assignment.What you can not do in C# (And I think it was the right design decision) is something like this:
The problem here is that it is very similar to the usual equals operator
==. There are cases when this code is intentional, but usually it is a typo which is very difficult to find. Compare it with this:When you are looking for a bug in your code, you can easily overlook this.