Alfie Jones Alfie Jones - 2 years ago 65 Question

I get an error when trying to check if an item is in a dictionary

Bellow is my vb code, I am trying to loop through all the words inputted and place all of the unique words into a dictionary with their position. I get this error though and I don't know how to fix it. Please, can I have any suggestions; thanks.

The error:Object reference not set to an instance of an object.

Public Class Form1
Dim sentence() As String
Dim uniqueWords As Dictionary(Of String, Integer)

Private Sub creatSaveBtn_Click(sender As Object, e As EventArgs) Handles creatSaveBtn.Click
sentence = sentenceInputTxt.Text.ToLower.Split(" ")

For Each word In sentence
If Not uniqueWords.ContainsKey(word) Then
uniqueWords.Add(word, uniqueWords.Count + 1)
End If
End Sub
End Class

Answer Source
Dim uniqueWords As New Dictionary(Of String, Integer)

also you could:

Dim uniqueWords As List(Of String) = sentenceInputTxt.Text.ToLower.Split(" "c).Distinct().ToList()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download