Reputation: 82186
Question:
Why does the below code (not written by me) even compile ?
I mean apart from the fact that option strict is off and option infer is on...
If Not actdate.DayOfWeek = DayOfWeek.Saturday And Not actdate.DayOfWeek.Sunday Then
...
End If
if (!(actdate.DayOfWeek == DayOfWeek.Saturday) & !actdate.DayOfWeek.Sunday) {
...
}
Upvotes: 8
Views: 1356
Reputation: 941457
The accepted answer is not correct, operator precedence in VB.NET ensures that the logical version of And operator is used, same one as AndAlso. Both the left-hand and right-hand operands are of type Boolean thanks to the Not operators being used. Precedence in VB.NET is relational > Not > And. In C# it is ! > relational > &. Or to put it another way, you don't need parentheses in VB.NET like you do in C#.
The Not operator in Visual Basic accepts a Boolean or numeric expression. Just like in C#, an enum value is implicitly convertable to an integral value type that matches the Enum's base type. Integer in this case. A numeric value of 0 converts to False. Since DayOfWeek.Sunday's underlying value is 0, the Not expression always produces True.
So this is acceptable syntax. You do however get a warning for this code, very similar to the error you get in C#:
warning BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Produced by the Sunday enum member used in the actdate.DayOfWeek property expression. That is certainly a code smell. Short from not ignoring warnings, you can turn that warning into an error. Project + Properties, Compile tab, Warning configuration section. Change the "Instance variable accesses shared member" setting from Warning to Error.
Upvotes: 8