For string values use String.IsNullOrEmpty. For other values just use the standard value Is Nothing
or value Is not Nothing
.
The problem with your code is that you're calling String.IsNullOrEmpty
on result.Properties("DisplayName")(0).ToString()
. If any of the expressions result
, Properties("DisplayName")
, or (0)
is null then it fails. Furthermore (0)
implies an array. Is it actually an array? If so then you also need to ensure the array is not empty. Breaking up this query would help resolve this issue but VB.NET also supports the null-conditional operator so that is preferable.
But null conditional won't help with an empty array. You also call the expression again inside the If
so you can dramatically simplify this code by just breaking it up.
Dim itemName As String = If(result?.Properties("DisplayName")?(0)?.ToString(), "")
The above code evaluates the expression and returns either the final value or nothing if anything in there is not set. Then the If
function is used to return either the (non-nothing) value or the empty string. All that replies your existing if-else
.
If Properties("DisplayName")
is actually an array but is empty then the above code may still fail. You should test that scenario.