Initializing a StringCollection from My.Settings to avoid null reference exception

575 Views Asked by At

I am specifying a System.Collections.Specialized.StringCollection named MyCollection in My.Settings, and upon first use to add a string, a null reference exception is being thrown (i.e. MyCollection is Nothing).

The syntax to add a string is simply:

My.Settings.MyCollection.Add(myString)

How can I initialize a StringCollection from My.Settings if it is null upon first use?

There have been reports of .NET Framework conflicts and StringCollections in My.Settings. Thus, I have .NET Framework 4.6 specified in the project's app settings.

2

There are 2 best solutions below

4
Caius Jard On BEST ANSWER
  • Open the project properties, settings, and click the 3 dots button to open the string collection editor.
  • Add a single string and Click OK
  • Open the editor again and remove the string you added

Now your settings grid should look like this:

enter image description here

Instead of this:

enter image description here

And in runtime your settings will be a collection with 0 entries instead of a Nothing collection i.e. it won't crash when you try to use it

1
David On

You will need to check if the StringCollection is nothing using a conditional statement:

If (My.Settings.MyCollection Is Nothing) Then
    My.Settings.MyCollection = New System.Collections.Specialized.StringCollection() ' you probably won't need to fully qualify this, but I have it for visibility
End If
My.Settings.MyCollection.Add(myString)