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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With