Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with IIF function in VB.NET

Tags:

.net

vb.net

I am looking at a few lines of VB code and am not sure why the last WriteLine is failing. It seems as if the ToUpper() function is trying to be evaluated (will work if not calling this function on the string) even if the condition clearly evaluates to false and should just output the "mydefault" hard coded string in this example. I know that the Nothing keyword is similar to the default in C# but I think the issue really lies with how the IIF function evaluates it's trees.

Does anyone know the reason this code throw the NullReferenceException?

Module Module1
    Sub Main()
        Dim x As String = "a"
        Console.WriteLine(String.Format("y:{0}", IIf(String.IsNullOrEmpty(x) OrElse x Is Nothing, "mydefault", x.ToUpper())))

        Dim y As String = String.Empty
        Console.WriteLine(String.Format("z:{0}", IIf(String.IsNullOrEmpty(y) OrElse y Is Nothing, "mydefault", y.ToUpper())))

        Dim z As String = Nothing
        Console.WriteLine(String.Format("x:{0}", IIf(String.IsNullOrEmpty(z) OrElse z Is Nothing, "mydefault", z.ToUpper())))

        Console.ReadLine()
    End Sub
End Module
like image 818
JBone Avatar asked Mar 20 '26 08:03

JBone


1 Answers

IIF is a relic and evaluates both conditions as you describe. Try using If instead.

Module Module1
    Sub Main()
        Dim x As String = "a"
        Console.WriteLine(String.Format("y:{0}", If(String.IsNullOrEmpty(x) OrElse x Is Nothing, "mydefault", x.ToUpper())))

        Dim y As String = String.Empty
        Console.WriteLine(String.Format("z:{0}", If(String.IsNullOrEmpty(y) OrElse y Is Nothing, "mydefault", y.ToUpper())))

        Dim z As String = Nothing
        Console.WriteLine(String.Format("x:{0}", If(String.IsNullOrEmpty(z) OrElse z Is Nothing, "mydefault", z.ToUpper())))

        Console.ReadLine()
    End Sub
End Module
like image 190
Craig Johnson Avatar answered Mar 23 '26 04:03

Craig Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!