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
  • 18,045
  • 5
  • 28
  • 75
Karuntos
  • 61
  • 2
  • 11

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
  • 18,045
  • 5
  • 28
  • 75