Quick Tip: IIf isn’t doesn’t like null values!

Quick Tip

I’ve spent a good day beating my head up against a wall, and discovered that our VB ternary friend can be a little unfriendly at times…For those if you still in Visual Basic land (I delve back and forth these days), you know that there is no default ternary operator built into the language. However there is a helpful function that gives you the same functionality. In my case, I was doing some simple string formatting type stuff:

Dim StatusText As String
StatusText = String.Format("Magic code says: {0}", IIf(MagicObject Is Nothing, "Out of Order.", MagicObject.Status.ToString())

However, running this code gives you a lovely NullReferenceException. After some more head-banging-wall action and a wonderful nugget of wisdom from StackOverflow, I realized the reason. IIf is a function provided by the VB.Net framework, it is not it’s own operator, like the x ? y : z code works in C#. Therefore, if a null value is passed into a function, that isn’t expecting it, it’s going to yell at you, instead of short circuiting the evaluation, as you’d expect.

The solution? Use the If operator that became available a while back:

Dim StatusText As String
StatusText = String.Format("Magic code says: {0}", If(MagicObject Is Nothing, "Out of Order.", MagicObject.Status.ToString())

Sometimes one little redundant character makes all the difference… Enjoy!

About these ads

What are your 10 bits on the matter? I want to know!

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s