r/dotnet • u/Userware • 3d ago
Promotion C# 15 "unsafe" code: interactive tutorial + WebAssembly online playground
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.
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.
3
u/Fexelein 3d ago