6

I like to confirm that array is created, how can it be done? There is no nul keyword?

Dim items As Array = str.Split("|")
if (items=null)  then ???
1
  • 3
    The Split statement WILL create an array- no need to check. You can just use the .Length property to make sure there are items in it. Commented Mar 13, 2009 at 12:58

6 Answers 6

26

To check if an object is null in VB.Net you need to use the Nothing keyword. e.g.

If (items is Nothing) Then
    'do stuff
End If

However string.Split() never returns null, so you should check the input string for null rather than the items array. Your code could be changed to something like:

If Not String.IsNullOrEmpty(str) Then
    Dim items As Array = str.Split("|")
    'do stuff
End If
Sign up to request clarification or add additional context in comments.

3 Comments

If the string variable is empty and you do a split on it, the array will still contain 1 item, therefore items will always not be nothing.
mdresser: You have actually answered the question as asked in the title "VB.NET missing isNull() ?", but the answer doesn't make sense in terms of the code sample given. If I were you I'd edit the answer to state that fact. Hope this helps.
@Binary Worrier: thanks for the suggestion. I'll adjust my answer very soon.
7

Try using String.IsNullOrEmpty on your string variable before splitting it. If you attempt to split the variable with nothing in the string the array will still have one item in it (an empty string), therefore your IsNothing checks on the array will return false.

Comments

3

String.Split can never return null. At worst, it can return an array with no elements.

2 Comments

No, the returned array always has at least one item.
@Guffa: not true. If you use StringSplitOptions.RemoveEmptyEntries you can get an empty array back.
2

Use "Is Nothing" to test for Null in VB.NET.

If items Is Nothing Then

End If

Comments

1

The keyword for null in VB is Nothing.

However, this is not what you want to use in this case. The Split method never returns a null reference. It always returns a string array that has at least one item. If the string that you split was empty, you get an array containing one string with the length zero.

So, to check if you get that as result you would do:

Dim items As String() = str.Split("|")
If items.Length = 1 and items(0).Length = 0 Then ...

It's of course easier to check the input first:

If str.Length = 0 Then ...

Comments

0

For a one liner do this:

destinationVariable = if(myvar is nothing, "", myvar)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.