In VB 2008, I have a class that I use to store options for my application. The class is serialized to an .xml file to keep the options from one run to the next. I have a list of titles which has been 4 in length, so I simply showed them in the class definition like so:
Public Class Options
' System options
Public blnDisplayExcel As Boolean
Public strUserCategory1 As String
Public strUserCategory2 As String
Public strUserCategory3 As String
Public strUserCategory4 As String
There are also methods to save to a .xml file and retrieve from the .xml file. (Thanks, RonaldBiemans, for the original code.)
Now, I'm expanding the number of categories to 20, and it's going to be much more efficient to handle them as an array rather than 20 separately named properties. But I'm not sure how to accomplish that. If I just define a property as
Public strUserCategory(20) As String
I get "Object reference not set to an instance of an object" when I try to set strUserCategory(1)="XYZ".
I tried restructuring it as:
<System.Runtime.Serialization.OptionalField()> Private pstrUserCategory(20) As String
Public Property strUserCategory(ByVal i As Integer) As String
If i < 1 Or i > 20 Then
Throw New Exception("Out of range 1-20")
Set(ByVal value As String)
pstrUserCategory(i) = value
(The OptionalField attribute is there so deserializing the class with a new option doesn't generate an exception.) This gives the same "Object reference not set..." exception when I execute the Set code.
I'm not sure how I'm supposed to initialize the array. This feels like it should be simple, but somehow I'm not seeing it. FWIW, there is currently no New method for the class; should I be doing something there?