bhylu.com

Advertisements

C# Classes and Objects

Expose a reservation operation instead of a public field that callers can assign arbitrarily.

How it works

A class combines state with operations that preserve its rules. A private field prevents direct outside assignments, while the public interface should express meaningful domain actions. This session starts with zero reservations and a fixed capacity. Every accepted update must leave reserved between zero and capacity. Encapsulation helps because the rule can be reviewed in one place instead of relying on every caller to remember the same check.

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)
    {
        var session = new Session();
        Console.WriteLine($"Accepted: {session.Reserve(4)}");
        Console.WriteLine($"Too many: {session.Reserve(9)}");
        Console.WriteLine($"Reserved: {session.Reserved}");
    }
}

internal sealed class Session
{
    private int reserved;
    public int Reserved => reserved;
    public bool Reserve(int count)
    {
        if (count < 1 || count > 10 - reserved) return false;
        reserved += count; return true;
    }
}

Expected result

Accepted: True
Too many: False
Reserved: 4

The subtraction check is safe because the invariant already bounds reserved. Rejection happens before mutation, so the old state remains valid. Reserved is a read-only computed property from the caller’s perspective. Static members belong to the type; instance members use an object’s own state. Creating a second Session would create independent reservation state.

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