0

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 Answers2

1

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)
David
  • 5,877
  • 3
  • 23
  • 40
  • Thanks, but testing for nullity fails because the collection wasn't initialized. (I tried this before asking the question). You have to follow the procedures provided by @Caius Jard. –  Aug 10 '21 at 20:02
0
  • 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

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • I figured it out myself before coming back to look at answers, and did exactly this, and it worked. –  Aug 10 '21 at 20:04
  • 1
    I always thought it was a bit strange that Microsoft put the default as Nothing, because it's not very intuitive for the user.. maybe they assumed it would always be filled with at least one setting.. – Caius Jard Aug 11 '21 at 05:23
  • Yes - it's truly strange. Lists are not Nothing after using `Dim myList As New List(Of String)`. I just didn't click on the Items (`...` button) in Settings, then add one empty string. –  Aug 11 '21 at 19:01
  • 1
    Well, lists are nothing if you say `Dim myList as List(Of String)`.. but I get your point - I couldn't ever see the use case for anyone adding a setting of a string collection type but it not actually being usable.. – Caius Jard Aug 11 '21 at 19:11