Lesson 2 of 24
In progress
Your first console program
Print output, read input, handle a missing value, and see how top-level statements map to a class with a Main method.
A console program reads text and writes text. That is enough to learn the language’s shape, and it is the same shape a web handler uses: take input, decide, produce output.
What you will learn
- Write output with
Console.WriteLineand interpolation. - Read a line and handle a null return.
- Understand what top-level statements compile to.
Output
string name = "Ana";
int count = 3;
Console.WriteLine("Hello, " + name);
Console.WriteLine($"You have {count} item{(count == 1 ? "" : "s")}.");
Console.WriteLine("Total: {0:C}", 1299.5);
String interpolation with $ is the readable default. The expression inside the braces can be any expression, including a conditional, which the third line avoids by using a format string instead.
{0:C} formats as currency using the current culture, which is convenient for a console app and wrong for machine-readable output. For that, use the invariant culture explicitly:
using System.Globalization;
Console.WriteLine(1299.5.ToString("F2", CultureInfo.InvariantCulture));
Console.Write omits the newline, which is how prompts stay on one line.
Input
Console.Write("Your name: ");
string? input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("No name given.");
return;
}
Console.WriteLine($"Hello, {input.Trim()}");
ReadLine returns string? because input can end before a line is read — for example when stdin is a file that ran out. With nullable reference types enabled, the compiler warns if you use the value without checking, which is exactly the bug that would otherwise appear in production.
string.IsNullOrWhiteSpace covers null, empty and whitespace in one call, and it is the right check for a text field.
Reading numbers
Console.Write("Quantity: ");
string? raw = Console.ReadLine();
if (int.TryParse(raw, out int quantity) && quantity > 0)
{
Console.WriteLine($"Ordering {quantity}");
}
else
{
Console.WriteLine("Enter a positive whole number.");
}
TryParse returns a bool and writes the result through out. It never throws, which makes it the right tool for user input; int.Parse throws FormatException when the text is not a number.
The out int quantity declaration is inline, so the variable is scoped to the enclosing block. The && short-circuits: when parsing fails, the comparison does not run.
For decimals, use decimal.TryParse and pass the culture when the input format is fixed:
decimal.TryParse(raw, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal price);
Top-level statements
Console.WriteLine("one");
Console.WriteLine("two");
The compiler generates a class with a Main method containing those statements. You can still declare local functions and types in the same file:
Console.WriteLine(Describe(3));
static string Describe(int n) => n > 0 ? "positive" : "not positive";
Top-level statements must come before any type declarations in the file. A project can have only one file with them, because there is only one entry point.
If you prefer the explicit form, it is still fully supported:
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"args: {args.Length}");
}
}
args holds the command-line arguments in both forms.
Exit codes
if (args.Length == 0)
{
Console.Error.WriteLine("usage: app <name>");
return 1;
}
A return in top-level statements becomes the process exit code. Returning non-zero tells a script or CI job that the program failed, which matters as soon as the program is used by anything other than a person.
Console.Error writes to standard error, keeping error messages separate from normal output. That separation is what lets a caller pipe the output to a file and still see failures.
A complete example
Console.Write("Item: ");
string? item = Console.ReadLine();
Console.Write("Price in rupees: ");
string? priceText = Console.ReadLine();
if (string.IsNullOrWhiteSpace(item) || !decimal.TryParse(priceText, out decimal price))
{
Console.Error.WriteLine("Need an item name and a numeric price.");
return 1;
}
decimal tax = Math.Round(price * 0.18m, 2);
Console.WriteLine($"{item.Trim()}: {price:F2} + {tax:F2} tax = {price + tax:F2}");
return 0;
The m suffix marks a decimal literal. Math.Round(..., 2) with a decimal keeps the value exact to two places, which is why money should not travel through double.
Culture and formatting
A console app inherits the machine’s culture, which changes how numbers and dates print and parse. A test that passes on one machine can fail on another for this reason alone.
For anything that will be parsed by a program, format and parse with CultureInfo.InvariantCulture. For anything a person reads, the current culture is usually right. A program that reads a number in one culture and writes it in another produces output that no parser can consume reliably, which is why the boundary deserves an explicit choice rather than an inherited default.
Using int.Parse(Console.ReadLine()) and letting a typo crash the program. TryParse handles the same input without an exception, which is what a prompt needs.
Write a program that asks for a name and an age, rejects a blank name or a non-numeric age, and prints both back. Return a non-zero exit code on bad input.
Show solution
Console.Write("Name: "); string? name = Console.ReadLine(); Console.Write("Age: "); string? ageText = Console.ReadLine(); if (string.IsNullOrWhiteSpace(name) || !int.TryParse(ageText, out int age) || age < 0) { Console.Error.WriteLine("Need a name and a non-negative age."); return 1; } Console.WriteLine($"{name.Trim()} is {age} years old."); return 0; IsNullOrWhiteSpace and TryParse cover the two failure modes without exceptions, and the || chain short-circuits so age is only compared after a successful parse. The exit code lets a script detect the failure.
Recap
Console.WriteLinewith interpolation is the readable way to print; use the invariant culture for machine output.ReadLinereturnsstring?; check it withIsNullOrWhiteSpacebefore use.TryParsehandles bad input without exceptions, andreturnsets the exit code.
Next, variables and types, including the decimal type that money needs.
Why does ReadLine return a nullable string?
Can I clear the console?
Progress is saved in this browser only. No account, no email.