I have scoured the internet looking for a solution to this problem but the null exception remains. Basically I am getting System.NullReferenceException error when attempting to add values to a nested dictionary.
Here is my code.
Public Dict1 as New Dictionary(Of Integer, Dictionary(Of String, String))() 'Tried with and without()
Sub CreateDict(Length As Integer)
Dim key As Integer
Dim CmdName As String
Dim CmdValue As String
key = 0
CmdName = "UnusedCmd"
CmdValue = "NotAFolder,NotAFolder,NotAFolder,NotAFolder,NotAFolder,Read"
While key <= Length
Dim CmdDict As New Dictionary(Of String, String)
CmdDict.Add("Name", CmdName) 'Method 1 of Adding
CmdDict.Add("Command", CmdValue) 'Method 1 of Adding
'CmdDict("Name") = CmdName 'Method 2 of Adding Both seem to work as evidenced by msgbox
'CmdDict("Command") = CmdValue 'Method 2 of Adding Both seem to work as evidenced by msgbox
MsgBox(CmdDict("Name")) ' Returns UnusedCmd
MsgBox(CmdDict("Command"))' Returns NotAFolder,NotAFolder,NotAFolder,NotAFolder,NotAFolder,Read
MsgBox(key) 'Returns 1
Dict1.Add(key, CmdDict)
key = key + 1
CmdDict = Nothing 'Error Occurs whether or not this is commented out
End While
End Sub
Note this code was adapted from my original project which was in VBA for outlook 2016. I am trying to readapt this code to be an outlook addin.
I have tried replacing the "As" terms with "=" and I have also tried
Dim CmdDict As Dictionary(Of String, String) = New Dictionary(Of String, String)
For both dictionaries but this didn't work. I have tried everything that I can think of / find please help.
Could it have something to do with it being a public dictionary? I saw someone else using a public dicitonary and they're solution was to add new which I new I had to do otherwise no object would be created.
EDIT:
I just tried a regular dictionary as a public variable and it failed as well. So it appears to have nothing to do with being Nested. I will continue looking into the public object issue.
EDIT 2:
Just Tried adding Dict1 to Public Class Still not working.
Public Class GlobalVariables
Public Shared Dict1 As Dictionary(Of Integer, Dictionary(Of String, String)) = New Dictionary(Of Integer, Dictionary(Of String, String))
End Class
After doing this Dict1 was updated to GlobalVariables.Dict1
EDIT 3:
This code is within a VSTO Addin that I am creating based on macros that I wrote in Outlook VBA. I am using Visual Studio Community 2015. The location of the code is as follows
Edit 4: Duplicate? I agree I thought that this was a duplicate answer as well but I couldn't anywhere else where the answer was to move the Create Object from Public to within a Sub for a public variable. But the rest of the question is very similar to others agreed.