Search code examples
c#vb.netnullreferenceexceptionstringcollection

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


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.


Solution

    • 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