-1

I am writing a function that will allow me to input some values and then this will return this as a list. This is my code currently.

 Structure question
    Dim asking As String
    Dim answers As List(Of String)
End Structure

Private Function addQuestionToList(toAsk As String, answers() As String) As question
    addQuestionToList.asking = toAsk
    Dim listTemp As List(Of String)
    For i As Integer = 0 To answers.Count - 1
        listTemp.Add(answers(i))
    Next
    addQuestionToList.answers = listTemp
End Function



#Region "Quiz Questions"
    Dim GTAQuestions As List(Of question)
    Sub initializeGTAQuestions()
        GTAQuestions.Add(addQuestionToList("Some Question", {"answer1", "answer2"}))
    End Sub
#End Region
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
ipro_ultra
  • 131
  • 2
  • 9
  • The error that is giving me is "Object reference not set to an instance of an object." – ipro_ultra Feb 04 '15 at 11:17
  • you need to instanciate GTAQuestions -> DIM GTAQuestions as new List(of question) – Martin Moser Feb 04 '15 at 11:20
  • 1
    Nearly all NullReference Exceptions have the same set of causes. See [NullReference Exception in Visual Basic](http://stackoverflow.com/a/26761773/1070452) for help on this. And not for nothing, but you should probably learn how to accept answers people work up for you. – Ňɏssa Pøngjǣrdenlarp Feb 04 '15 at 11:57

2 Answers2

0

Change your code:

Dim GTAQuestions As List(Of question) Sub initializeGTAQuestions() GTAQuestions.Add(addQuestionToList("Some Question", {"answer1", "answer2"})) End Sub

with this:

Dim GTAQuestions As New List(Of question)
Sub initializeGTAQuestions()
    GTAQuestions.Add(addQuestionToList("Some Question", {"answer1", "answer2"}))
End Sub
0

You need to initialize each instance of the structure. One option is to include a custom new method in your structure, so your structure and function will look like this:

Structure question
  Dim asking as String
  Dim answers as List(Of String)

  Public Sub New (ByVal _asking as String, ByVal _answers as List(Of String))
    asking = _asking
    answers = _answers
  End Sub
End Structure

Private Function addQuestionToList(ByVal asking as String, ByVal answers() as String) as question
  Dim lstAnswers as New List(Of String)
  For Each answer As String in answers
    lstAnswers.Add(answer)
  Next
  Return New question(asking, lstAnswers)
End Function
Sparhawk_
  • 162
  • 1
  • 1
  • 9