Best Practice to check for null/empty values

Ryan Lashway 61 Reputation points
2023-01-12T19:11:43.23+00:00

What is the best method to test for a null/empty value, the following code gives me an error every time I run it when I hit a record with no DisplayName value in activedirectory I get the following error:

"Index was out of range. Must be a non-negative and less than the size of the collection.

Parameter name: index"

If there is a value in the DisplayName the code runs fine.

Dim ItemName as String = Nothing
If Not String.IsNullOrEmpty(result.Properties("DisplayName")(0).ToString()) Then
ItemName = result.Properties("DisplayName")(0).ToString
Else
ItemName = ""
End if

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,053 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,361 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,768 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 56,271 Reputation points
    2023-01-12T19:20:58.2533333+00:00

    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.