C#: Did if( a = b) lose its sting

One of the common typo of using if (a = b) in place of if (a == b) gave a lot of grief to programmers working in C and C++. If you make the typo, you have an expression that is always true if b is not 0 (mostly it isn't) and the compiler is not even polite enough to warn you. So many people taught themselves to use the inverted comparison as in

 int a = 1;if(a == 2)   printf("Hello");if  (2 == a) // inverted   printf("Hello");

People believed the inverted comparison was better because if you typed = instead of == you'd get a compilation error indicating that the "left operand of = must be a lvalue" . I always thought that a person who remembers to type the inverted expression will anyway remember to not-type = in place of ==. I felt uneasy to see expressions this way.

C# allows only boolean expression for comparison. This almost removed the chances of the typo to exist. You can make the same typo only if a is a boolean type. So the following code will fail to compile in C#

 int a = 1;if (a = 2)    Console.WriteLine("Yea");

Stating "Cannot implicitly convert type 'int' to 'bool'". So this virtually eliminates the chances of the typo leading to a bug. In case you do have something as below

 bool cond = false;bool othercond = true;if(cond = othercond)   Console.WriteLine("Yea");

it can potentially lead to a bug if you did not intend the =. As again there is no warning and one bug just sneaks in. Before this leads you to believe that a bug can sneak in only if the lvalue is boolean you need to carefully look at following

 class MyClass{    public static implicit operator bool(MyClass mc)    {        return true;    }}
MyClass mc1 = new MyClass();MyClass mc2 = new MyClass();if (mc1 = mc2)    Console.WriteLine("Yea again");

This will compile without an warning because the class has an implicit cast to bool.  The compiler will not complain and you again have the same sneaky bug in your code.