I found this other stack overflow question about files and directories, and the answer included this statement:
bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
== FileAttributes.Directory;
His question was about .net, and I was coding in C# .net in Visual Studio. Is the ability to have both an assignment operator and an equals operator in the same statement work for all .net languages or is it specific to certain ones? Also, can I get an explanation for how the above code works? Assuming that path refers to a directory, I’d expect isDir to be true, but can anyone explain why?
The equality test performed by the
==operator takes precedence over the assignment performed by the=operator. Therefore, theisDirvariable will be set equal totrueif the two sides of the==operator are equal, otherwise it will be set tofalse. In other words, it’s the equivalent of saying:This is possible in VB.NET. I cannot answer for other languages. In VB.NET, the equivalent would be:
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: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 expressiony = 5not only assigns the value 5 to the variabley, but it also evaluates to the value of 5 as well. So, when you setxto the value of that expression, it gets set to 5 as well. In VB, however, the result is very different:In VB, the compiler will assume that the expression
y = 5is an equality test, so it will evaluate toFalse. Therefore, it will attempt to setx = Falsewhich may or may not work depending on the value ofOption Strict.