The equality test performed by the ==
operator takes precedence over the assignment performed by the =
operator. Therefore, the isDir
variable will be set to true
if both sides of the ==
operator are equal, otherwise it will be set to false
. In other words, this is equivalent to saying:
if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory) isDir = true; else isDir = false;
This is possible in VB.NET. I cannot answer for other languages. In VB.NET, the equivalent would be:
Dim isDir As Boolean = ((File.GetAttributes(path) And FileAttributes.Directory) = FileAttributes.Directory)
Since VB uses the same character ( =
) for assignment and equality operators, it determines which operation you perform based on context. The VB compiler is smart enough to know that the first =
operator is the destination, and the second the equality test. However, this is clearly confusing, so it is often discouraged for readability. This is especially confusing for people with experience in other languages. For example, in C # you can do the following to set two variables to the same value:
int y; int x = y = 5;
The reason that arises in C # is that =
always an assignment operator, and the assignment expression always evaluates (returns) the value that was assigned. Therefore, in this case, the expression y = 5
not only assigns the value 5 to the variable y
, but also evaluates the value 5. So, when you set the value x
to the value of this expression, it is also set to 5. In VB, however, the result is very different:
Dim y As Integer Dim x As Integer = y = 5
In VB, the compiler will assume that the expression y = 5
is an equality test, so it will evaluate to false
. Therefore, it will try to set x = False
, which may or may not work depending on the value of Option Strict
.