bhylu.com

Advertisements

C# If and Else

Classify a request using ordered conditions and reject impossible values before ordinary categories.

How it works

An if statement selects work from a boolean condition. An else-if chain takes the first matching branch, which is useful when categories are exclusive. Decide whether exact thresholds belong to the lower or upper category before writing comparisons. A workshop request of zero can mean an invalid request rather than an empty successful booking, so give it a deliberate branch. Braces make later changes safer and keep the controlled statements visible.

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.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;

internal static class Program
{
    private static void Main(string[] args)
    {
        int requested = 6;
        if (requested <= 0) Console.WriteLine("Request must be positive");
        else if (requested <= 4) Console.WriteLine("Small table");
        else if (requested <= 8) Console.WriteLine("Large table");
        else Console.WriteLine("Split the booking");
    }
}

Expected result

Large table

Four belongs to the small table and eight to the large table under this policy. Only one label is printed. A useful test set includes zero, one, four, five, eight and nine. Nested conditions may express dependent rules, but extracting a named predicate or returning early after invalid input can make deep branching easier to review.

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