The equality test performed by the ==
operator takes precedence over the assignment performed by the =
operator. Therefore, the isDir
variable will be set equal to true
if the two sides of the ==
operator are equal, otherwise it will be set to false
. In other words, it's the equivalent of 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 both it's assignment and equality-test operators, it determines which operation you are performing based on context. The VB compiler is smart enough to know that the first =
operator is an assignment and the second one is an equality test. However, this is obviously confusing, so it is often discouraged, for readability sake. It's particularly confusing to people with backgrounds in other languages. For instance, in C#, you could do the following to set two variables to the same value:
int y;
int x = y = 5; // Both x and y will be set to 5
The reason that happens in C# is because =
is always an assignment operator, and the assignment expression always evaluates to (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 it also evaluates to the value of 5 as well. So, when you set x
to the value of that expression, it gets set to 5 as well. 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 attempt to set x = False
which may or may not work depending on the value of Option Strict
.