0

I want to create a specified number of strings in a VB.NET Console Application. I've tried this code but it throws an exception:

NullReferenceException: Object Reference not set into an instance of an Object.

This is the code:

Module RandStrConsole

Dim r As New Random
Dim s As String
Dim result As System.Text.StringBuilder
Dim sb As System.Text.StringBuilder
Dim MaxChar As Integer


Sub Main()

    Console.Write("Enter String: ") : s = Console.ReadLine
    Console.Write("Maxchar: ") : MaxChar = Console.ReadLine

    For i As Integer = 1 To MaxChar

        Dim idx As Integer = r.Next(0, s.Count - 1)
        result = sb.Append(s.Substring(idx, 1)) 'NullReferenceException: Object Reference not set into an instance of an Object.
        result.ToString()

    Next

    Console.WriteLine(result)
    Console.ReadKey()


End Sub

End Module

The commented section indicates where the exception happened.

Visual Vincent
  • 17,424
  • 5
  • 24
  • 66
Karuntos
  • 61
  • 1
  • 11
  • If my answer solved your problem then please remember to mark it as accepted by pressing the tick/check mark on its left. -- More info can be found here: [**How does accepting an answer work?**](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Visual Vincent Feb 19 '17 at 10:16
  • Glad I could be of help! Good luck with your project! – Visual Vincent Feb 19 '17 at 10:31
  • 1
    Thanks @VisualVincent, I hope you can reach more people to help! – Karuntos Feb 19 '17 at 10:43
  • Your issue explained in detail [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – zaggler Feb 19 '17 at 13:57

1 Answers1

-1

You forgot to initialize the StringBuilders. You must use the New keyword.

Dim result As New System.Text.StringBuilder
Dim sb As New System.Text.StringBuilder
Visual Vincent
  • 17,424
  • 5
  • 24
  • 66