CodeVideoNote
中文Workspace

C# · Original teaching example

C#: validate numeric input

This teaching case was authored to show a note format. It was not extracted from a real video or user note, and it has no invented timestamps.

Problem

A text field must become a number without throwing on invalid input.

Approach and limits

TryParse reports success and assigns the parsed value. Handle failure explicitly instead of silently using zero.

Example code

if (int.TryParse(input, out int count))
{
    Console.WriteLine(count);
}
else
{
    Console.WriteLine("Enter a whole number.");
}

Check it yourself

Input 12 should print 12; input twelve should show the validation message.