bhylu.com

Advertisements

C# Strings

Build a session label and distinguish string contents from the variables that refer to them.

How it works

string is a reference type whose text value is immutable. An operation such as concatenation creates a result instead of modifying the existing string’s characters. Assigning one variable to another can share the same immutable object safely, but reassigning either variable changes only that variable. Length counts UTF-16 code units, not necessarily user-perceived characters. A char is one UTF-16 code unit and is not a complete model of every Unicode character.

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)
    {
        string original = "Workshop";
        string saved = original;
        original += " 7";
        Console.WriteLine($"Current: {original}");
        Console.WriteLine($"Saved: {saved}; units: {saved.Length}");
        Console.WriteLine($"First: {saved[0]}");
    }
}

Expected result

Current: Workshop 7
Saved: Workshop; units: 8
First: W

saved continues to refer to the original text after original is reassigned to the concatenated result. The fixed first-character access is in bounds. For many incremental appends, StringBuilder can avoid repeated intermediate strings; use it when profiling or the construction shape justifies it. Search and comparison also need a deliberate culture or ordinal policy.

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