Console Input and Command-Line Arguments
Prerequisites: Type conversion
Reading from the keyboard
Console.ReadLine() reads one line of text typed by the user:
' illustrative: waits for keyboard input
Module Program
Sub Main()
Console.Write("What's your name? ")
Dim name = Console.ReadLine()
Console.Write("How old are you? ")
Dim age As Integer
If Integer.TryParse(Console.ReadLine(), age) Then
Console.WriteLine($"Hi {name}, next year you'll be {age + 1}.")
Else
Console.WriteLine($"Hi {name}, that doesn't look like a number.")
End If
End Sub
End Module
A typical session:
What's your name? Ada
How old are you? 36
Hi Ada, next year you'll be 37.
Input is always a String: parse it with TryParse and handle bad
input instead of crashing. Console.ReadKey() reads a single key press.
A simple menu loop
' illustrative: waits for keyboard input
Module Program
Sub Main()
Do
Console.WriteLine("1) Say hello 2) Show time Q) Quit")
Dim choice = Console.ReadLine()
If choice Is Nothing Then Exit Do ' input ended (for example, Ctrl + Z)
Select Case choice.Trim().ToUpper()
Case "1"
Console.WriteLine("Hello!")
Case "2"
Console.WriteLine(Date.Now.ToShortTimeString())
Case "Q"
Exit Do
Case Else
Console.WriteLine("Unknown choice")
End Select
Loop
End Sub
End Module
ReadLine returns Nothing when the input stream ends — for example,
when the user presses Ctrl + Z then Enter (Windows) or Ctrl + D
(Linux/macOS), or when input is redirected from a file. Checking for it
avoids a crash (or an endless loop).
Command-line arguments
Main can take the arguments as a string array:
' illustrative: run as dotnet run -- 3 4
Module Program
Function Main(args As String()) As Integer
If args.Length <> 2 Then
Console.Error.WriteLine("Usage: add A B")
Return 1
End If
Console.WriteLine(CInt(args(0)) + CInt(args(1)))
Return 0
End Function
End Module
7
- Everything after
--indotnet run -- ...is passed to your program. - Declaring
Mainas aFunction ... As Integerreturns an exit code: 0 means success, anything else signals an error to scripts and CI pipelines. Console.Error.WriteLinewrites to the error stream, where usage and error messages belong.