Visual Basic Conditionals
At my current job I write far more Visual Basic code than I do C# code. Having started programming in C++ in junior year of high school and using almost exclusively C++ and Java in college, I tend to favor C based languages. One of the more natural things about C(++/#) that I found lacking in Visual Basic was intelligent conditional testing.
For example:
Dim student as Student = Nothing If student IsNot Nothing And student.Name = "robber.baron" Then GiveStudentAnA(student) EndIf
var student as Student = null; if (student != null && student.Name == "robber.baron") GiveStudentAnA(student);
In the C# code when the conditional is a logical And (signified by the double ampersand) and the first condition fails it immediately exits the conditional. Since both values must be true to continue if the first is false the conditional fails and there is no need to evaluate the second condition.
In the Visual Basic code you will get a “Object Reference not set to Instance of Object” exception because Visual Basic does not implicitly have this feature. The test for null will fail but the second condition will still be evaluated! I never liked this feature and found it to be a concrete failure in Visual Basic.
Recently I discovered that of course Visual Basic allows you to do this. (The CLR is the CLR is the CLR. It is all common under the hood.) It just needs to you explicitly request this behavior using the AndAlso or OrElse keywords.
Dim student as Student = Nothing If student IsNot Nothing AndAlso student.Name = "robber.baron" Then GiveStudentAnA(student) EndIf
This is how you would properly translate the C# code above into Visual Basic.
If you wanted the inverse, you only wanted the right side condition to evaluate only if the left is true you could do the following:
Dim student as Student = new Student("robber.baron", "C") If student.Name = "robber.baron" OrElse Not student.Grade = "A" Then GiveStudentAnA(student) EndIf
Finally I can combine null checks and logic checks into a single conditional correctly.