VB.NET and If-statements, part 2: If and nullable variables
I blogged about VB.NET’s IIF-statements few years ago. As I mentioned back then, they are a handy way to shorten the code and to make it more readable but also a great way to introduce subtle bugs into our systems. Here’s the part 2 two that blog post, dealing with If statements and nullable variables.
Given the following VB.NET code:
Dim amount = 100 Dim newAmount As Integer? = If(amount = 100, Nothing, 50) Console.WriteLine("New value: {0}", newAmount)
With the first glance it’s quite obvious that the app will print “New value: ” as we’re setting newAmount to nothing. But when run, here’s what we see:
Strange. NewAmount isn’t “nothing” as we thought, it’s actually 0. To correct the issue, we have to cast the “nothing” to nullable integer:
Dim amount = 100 Dim newAmount As Integer? = If(amount = 100, CType(Nothing, Integer?), 50) Console.WriteLine("New value: {0}", newAmount)
And this time we get the desired output: