Home > API General > VB.NET and If…

VB.NET and If…

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

Dim MyVar As String = "My Value"

If MyVar = "My Value" Then
End If

For Each Item In ItemCollection
Next Item

While Running
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 )”

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: