1

Can someone please explain why Example 1 gives a NullReferenceException while Example 2 works fine

   Dim teachers As String()
   Dim Paragraph as string = "one,two"

Example 1

teachers(0) = "Mostafa"
teachers(1) = "Lina"

Example 2

teachers = paragraph.Split(",")

2 Answers 2

4

Firstly teachers is an String array.

Dim teachers As String() declares your string array but doesn't specify how many items are in the array or initialise any of them (it is a Null reference at this point)

Therefore trying to allocate a string to an item in the array fails (with a NullReferenceException) because it is not been initialised:

teachers(0) = "Mostafa" 'Fails
teachers(1) = "Lina"    'Also fails

String.Split is a function that "Returns a string array", so when you call it, the Null Reference is replaced with a reference to a string array created by the String.Split function, so this works:

teachers = "Mostafa,Lina".Split(","c)

Alternatively you can declare and initialise the String array with one line:

Dim teachers As String() = {"Mostafa", "Lina"}

Sign up to request clarification or add additional context in comments.

Comments

1

Because you never given the size for the Array, to initialize the memory for the required array length. So, as there's no initialization, array(0) will be null. Where as in the second case the Assignment will automatically initializes certain memory to the array, because the String.Split will always returns a array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.