Archive

Posts Tagged ‘Programming’

VB.NET and If…

In programming, the most basic code structures are assignment , condition, and iteration. From these basic blocks every program is constructed.

'Assignment
Dim MyVar As String = "My Value"

'Conditional
If MyVar = "My Value" Then
    DoOperation()
End If

'Iteration
For Each Item In ItemCollection
    DoWork(Item)
Next Item

While Running
    ProcessInput()
End While

In Visual Basic.NET, there are a few operators and a built in function which resemble conditional statements, therefore creating a source of confusion for many developers.

Function IIf ( Test As Boolean, IfTrue As Object, IfFalse As Object ) As Object

VB6, or classic visual basic has a built in function named IIf which will return one argument or another depending an the value of a Boolean argument. In Visual Basic.NET, this built in function can continue to be used by importing the Microsoft.VisualBasic namespace. One thing to keep in mind when using this is that as a function each argument is evaluated before the function is. If you provide a method such as a function or sub for either or both of the Object arguments IfTrue and IfFalse, the method will be evaluated despite the value of the Boolean argument Test. As such, this function should generally be avoided.

If ( Test As Boolean, IfTrue As Object, IfFalse As Object ) As Object

Also called a Ternary Conditional and seen in many other languages as “bool ? ifTrue : ifFalse”. While seemingly the only difference between the ternary If operator and the IIf function are the lack of an “I”, being an operator, only the applicable argument will be evaluated. This statement should be used exclusively instead of IIf.

If ( T, T ) Where T : Object As T

This coalesce operator will yield the value of the first argument if it does not evaluate to Nothing. If the first argument is Nothing, than the second operator will be evaluated and used. This is seen in the C# language as “var nonNull = NullableRef ?? DefaultRef”. Using this form as “Dim NonNull = If ( MyVar, DefaultValue )” is preferable to “Dim NonNull = If ( MyVar IsNot Nothing, MyVar, DefaultValue )”