r/dotnet • • 3d ago

Promotion C# 15 "unsafe" code: interactive tutorial + WebAssembly online playground

Post image

C# 15 brings some interesting changes to "unsafe" code, so we thought it would be useful to create a hands-on tutorial that starts with the basics AND also serves as an interacrive online playground.

It runs entirely in the browser: you edit the C# 15 code, compile it to WebAssembly and see the result immediately, without installation. (A desktop/laptop is recommended for the split-view experience)

Here's the link: https://xaml.io/s/Samples/UnsafeCodeTutorial?autorun=true&file=StartHere.cs

The tutorial has 10 short lessons, convering pointers, memory access, why unsafe code an be useful, safer alternatives like "Span<T>", and the new memory-safe rules.

Hope some of you find it useful.

15 Upvotes

8 comments sorted by

3

u/Fexelein 3d ago
using System;

class Program
{
    // c# 14: unsafe only affected the method body.
    // c# 15 now also requires callers to acknowledge the unsafe contract.
    static unsafe int CalculateSomething(int value)
    {
        return value * 2;
    }

    // c# 14: unsafe on the method provided an unsafe context for its entire body.
    // c# 15 requires unsafe to be explicitly scoped around pointer operations.
    static unsafe int ReadValue(int* pointer)
    {
        unsafe
        {
            return *pointer;
        }
    }

    static void Main()
    {
        int number = 42;

        // c# 14: int* pointer = &number; required an unsafe context.
        // c# 15 allows pointer declarations and address acquisition in safe code.
        int* pointer = &number;

        int result;

        // c# 14: result = ReadValue(pointer); was allowed in safe code.
        // c# 15 now requires the unsafe context to be added in the caller.
        unsafe
        {
            result = ReadValue(pointer);
        }

        Console.WriteLine($"ReadValue: {result}");

        int calculation;

        // c# 14: calculation = CalculateSomething(number); 
        // c# 15 now requires the unsafe context to be added in the caller.
        unsafe
        {
            calculation = CalculateSomething(number);
        }

        Console.WriteLine($"Calculation: {calculation}");

        // c# 14: unsafe(expression) syntax did not exist.
        // c# 15 allows unsafe context to be scoped to a single expression.
        int anotherResult = unsafe(ReadValue(pointer));

        Console.WriteLine($"Unsafe expression: {anotherResult}");

        // c# 14: int* numbers = stackalloc int[3]; required an unsafe context.
        // c# 15 allows stackalloc pointer conversion in safe code.
        int* numbers = stackalloc int[3] { 10, 20, 30 };

        // c# 14: pointer indexing required an unsafe context.
        // c# 15 still requires an unsafe context for pointer dereferencing.
        unsafe
        {
            Console.WriteLine($"First element: {numbers[0]}");
            Console.WriteLine($"Second element: {numbers[1]}");
            Console.WriteLine($"Third element: {numbers[2]}");
        }

        // c# 14: sizeof(int) required an unsafe context.
        // c# 15 allows sizeof on built-in unmanaged types in safe code.
        Console.WriteLine($"Size of int: {sizeof(int)} bytes");
    }
}

2

u/Userware 2d ago

Great stuff! Our tutorial only covered the basics, whereas this dives much deeper into the changes between C# 14 and C# 15. Very nice

1

u/Discordbothost 2h ago

sizeof(int) was already legal in safe C#14 code. the C#15 preview extends safe sizeof to other unmanaged types, so the last comparison comment overstates that change. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof

1

u/Fexelein 3d ago

Lesson 5 gave me a result that was performing slower than the safe example. Its probably not what the reader is expecting or what the author intended.

5. Speed
Adding 250,000 numbers, 10 times:
Safe: 9.6 ms
Unsafe: 10.7 ms
Same answer: True
Unsafe was 0.9x as fast.

1

u/Userware 2d ago

That's definitely strange, indeed. On Chrome on Windows, I get 1.3x, but on Safari 18 on an iPhone 12 mini, I get 0.9x just like you. It's compiled with Roslyn and runs the same .NET for WebAssembly as Blazor (in non-AOT mode). Definitely worth investigating...

1

u/Fexelein 3d ago

It would be a good addition to include the following to the tutorial or lessons somewhere, for the developers reading along and learning about these new features:

- The compiler settings required to enable the new features. e.g. preview and updated-memory-safety-features

- A link to the official microsoft documentation

2

u/Userware 2d ago

Thanks for the feedback. Good point! We've just updated the tutorial: line 14 mentions <AllowUnsafeBlocks>true</AllowUnsafeBlocks>, while lines 446-459 cover the documentation (for the C# 15 changes) and the "updated-memory-safety-rules" flag.

1

u/AutoModerator 3d ago

Thanks for your post Userware. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.