bhylu.com

Advertisements

C# Console Input

Check end of input and validation separately before treating a line as a booking.

How it works

Console.ReadLine can return null at end of input. A present line is still only text, so conversion and range validation must follow. This local exercise accepts one positive count up to twenty and returns a nonzero process status on rejection. ReadLine may allocate for a long line before validation, so this demonstration is not a hard memory cap for a hostile unbounded stream. A production ingestion boundary should bound transport framing before buffering a whole record.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Standard input fixture: type 6 and press Enter. Rejected-input cases are checked in review.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;
using System.Globalization;

internal static class Program
{
    private static void Main(string[] args)
    {
        string? line = Console.ReadLine();
        if (!int.TryParse(line, NumberStyles.None, CultureInfo.InvariantCulture, out int count) || count is < 1 or > 20)
        {
            Console.Error.WriteLine("Enter 1..20 places"); Environment.ExitCode = 2; return;
        }
        Console.WriteLine($"Requested: {count}");
    }
}

Expected result

Requested: 6

Provide six followed by Enter. The program prints success only after all checks pass. End of stream, an empty line and malformed or out-of-range numbers share one clear teaching error message. An interactive application may need retry, cancellation and more specific guidance rather than exiting after one attempt.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.

Advertisements