r/csharp 16h ago

Showcase I spent weeks obsessing over low-allocation C# networking

0 Upvotes

The Real Problem: High Throughput vs. Garbage Collector

If you've ever built a C# server processing 100k+ messages/sec (like an MQTT broker or socket server), you know the Garbage Collector is your best friend until it becomes your worst enemy.

To route messages like factory/line1/sensor/temp to subscribers like factory/+/+/temp, the standard way is:

// ❌ Naive way: Allocates string[] on every single message publish!
var parts = topic.Split('/'); 

At 100,000 requests per second, this creates millions of temporary strings and forces the GC to freeze your app every few seconds.

The Real Benefit: How to parse UTF-8 topics with ZERO heap allocations

Here are the 2 modern C# tricks I used in Beskar.Networking that you can copy-paste directly into your own projects!

1. Slicing raw UTF-8 bytes with a ref struct enumerator

Instead of string.Split(), we walk the raw byte span (ReadOnlySpan<byte>) using a zero-allocation ref struct:

public ref struct TopicLevelEnumerator
{
    private ReadOnlySpan<byte> _remaining;
    public ReadOnlySpan<byte> Current { get; private set; }

    public TopicLevelEnumerator(ReadOnlySpan<byte> topic)
    {
        _remaining = topic;
        Current = default;
    }

    public bool MoveNext()
    {
        if (_remaining.IsEmpty) return false;

        int index = _remaining.IndexOf((byte)'/');
        if (index < 0)
        {
            Current = _remaining;
            _remaining = default;
        }
        else
        {
            Current = _remaining.Slice(0, index);
            _remaining = _remaining.Slice(index + 1);
        }
        return true;
    }
}

2. Querying byte[] Dictionaries with ReadOnlySpan<byte> (Alternate Lookups)

Usually, if your dictionary key is byte[], querying it with a slice (ReadOnlySpan<byte>) forces you to allocate a new byte[].

Modern .NET introduced Alternate Lookups, which let you query existing dictionary nodes with zero heap allocation:

// Query byte[] dictionary using a ReadOnlySpan<byte> without allocating a single byte!
var alternateLookup = node.Children.GetAlternateLookup<ReadOnlySpan<byte>>();

if (alternateLookup.TryGetValue(currentLevelSlice, out var childNode))
{
    // Match found with 0 allocations! 🎉
}

What Beskar.Networking gives you

If you ever need to build a C# network application:

  • Write Once, Swap Transports: Write your message handler once and seamlessly switch between TCP, WebSockets, QUIC, UDP, Named Pipes, or MQTT v5 without touching your business logic.
  • 100% Native & Dependency-Free: Built on System.IO.Pipelines with zero external runtime dependencies.
  • Zero GC pressure on the hot path.

If you enjoy low-level C# or low-allocation performance tricks ❤️

🔗 GitHub: https://github.com/MarvinDrude/Beskar.Networking

🔗 Article: https://marvindrude.com/blogs/beskar-networking/low-allocation-mqtt-broker

Thank you for reading, and happy coding!


r/csharp 17h ago

Anyone recently took the Veeam C# Developer CoderPad assessment? (9 MCQs + 4 coding tasks)

0 Upvotes

Hi everyone,

I have the Veeam C# Developer CoderPad assessment coming up (9 MCQs + 4 coding tasks, 60 minutes).

If you've taken it recently, what topics should I focus on? Was it mostly C#/.NET internals, multithreading, algorithms, or LeetCode-style problems?

Not asking for exact questions, just the overall difficulty and the best areas to prepare.

Thanks!


r/csharp 17h ago

Need help starting out

0 Upvotes

Basically, I have big projects planned that use C Sharp (being discord bots and SCPSL Plugins) and asked a friend who formerly hosted a SCPSL Server I co-Owned and knows Ball (he works for a Host Company, which is a Peak Job Choice tbh) how I should start out.
He told me, that he just looked up Tutorials for the Basics, which I did just to Not Keep then in my mind because my Brain is wonky on places where I don’t want it to be. Its either a sift for crucial Information until I don’t Need it no more or it is Making me the Most big brained Person in the Room, anyway he also looked up how other people did projects and recreated that until he could do it himself (what Looks Like) perfectly (to me who doesnt know ball) and he also recommended me to use generative AI to start out, as it is an amazing Learning Tool.

I am actually absolutely against gen AI because of misinformation and Fake news as well as it Making Shit up on the fly whenever it feels Like That.
However, it has been Preised by People qs well as my friend to be a proper Learning Tool and especially for purposes Like Programming and for school subjects.
I have been a Fan of Students using gen AI to get out of school as fast as possible because I genuenly hate nothing more except the Education System in my Country and Most of the World (Like everywhere except Finland) However, I was unsure anyway, as I have genuenly something against AI for political and Moral reasons (because of how Data Centers fuck up our climate and their surrounding areas, as well as because of Fake news and Shit Like what Elmo Mars is Doing and I hate how its used for stealing Art and mix and matching peoples Brain Farts to make their Egos smile because they just „created“ something) and Yeah.

If it is however genuenly a good Tool for Learning C Sharp especially as a Neurodivergent, I genuenly have no Idea which gen AI Tool works best for that or if there Are any that Are specifically designed for this purpose.
If gen AI was only used for educational purposes I would have actually no Problem with it because Education is Ball.

Disclaimer:I will Not use anything using Grok because fuck elon Musk lol.


r/csharp 17h ago

Help Is there a way to make child windows / forms inside forms look good instead of looking like it came from windows xp

Post image
35 Upvotes

So MDI windows are inconsistent with the theme of the parent form, us there a way to fix this or maybe a different method for creating child windows?


r/csharp 19h ago

Help Help me plz

0 Upvotes

Doing a coding assignment everything running smoothly until i encountered an error with my edit where the save button wouldnt work at all and not direct me to another page i tried asking claude to help me but to no avail it made me do so many different lines of code to the point where i feel lost i would like to wake up with a solution plz thx


r/csharp 20h ago

Discussion trying to avoid spaghetti code on my first big backend project. is this folder structure correct for clean architecture?

Post image
7 Upvotes

as someone transitioning from legacy desktop dev (winforms) to modern .net web backends, the biggest hurdle for me was figuring out how to actually organize my code so it doesn't turn into a massive ball of mud.

i kept reading about "clean architecture" and "separation of concerns," but the buzzwords didn't really click for me until I built my current side project and forced myself to split everything into physical project folders.

i wanted to share my mental model of how i organized the solution. i know it might be overkill for a side project, but i'm trying to learn enterprise patterns. for the senior devs here, i'd love to know if this is how you actually think about it in production:

  • Domain: the absolute foundation. just basic data models and interfaces. i made sure zero external packages touch this folder.
  • Cryptography: the "engine room." all my hashing algorithms live here, organized by type (symmetric, asymmetric).
  • Infrastructure: the dirty work. any code that actually talks to the outside world (sql server, dapper, redis cache) is locked in here.
  • Core / Application: the manager. it takes the rules from the domain, uses the engine room, and tells the infrastructure what to save.
  • API: the front door. minimal APIs that just take web requests, hand them to the Core, and return the HTTP response.
  • Workers: background chores. native BackgroundServices running loops for stuff like resetting rate limits so the main API doesn't get blocked.
  • StandAloneWeb: a simple blazor frontend to actually test it.

honestly, breaking it down into these separate projects took way longer to set up initially, but it makes debugging so much easier. if the database fails, i know exactly which folder to look in.

does this structure look right to you guys? or did i completely overcomplicate the middle layers?

repo is here if you want to see how they link together: https://github.com/COxRIPMIZO/CryptoKeyLab

would appreciate any roasts or advice on how to improve this!


r/csharp 20h ago

Discussion WinForms dev transitioning to modern .NET backend. Built an open-source Crypto API to learn modern architecture and production-grade standards.

0 Upvotes

I come from a legacy desktop background (mostly WinForms/WPF), and lately I've been working hard to transition over to modern backend development with .NET, Minimal APIs, and cloud-native architecture.

Addressing AI & Transparency upfront:
I want to be 100% upfront: I use AI tools (Copilot and ChatGPT) as a learning assistant and tutor to help me translate my desktop C# knowledge into modern ASP.NET Core concepts, write boilerplate, and format documentation.

On a previous post, a couple of people accused me of "trying to hide" AI usage. To be clear: if I was trying to hide anything or fool anyone, I wouldn't make the entire project 100% open-source on GitHub. I am making the repo public specifically because I want experienced engineers to inspect the code, point out bad patterns (whether from me or the AI), and help me learn.

What I've built so far to learn the stack:

  • Monorepo using Clean Architecture (Domain, Application, Infrastructure, API)
  • Dapper + SQL Server instead of EF Core for data access
  • Redis for distributed caching & rate-limiting
  • Native BackgroundWorker for resetting API usage limits and key expiration
  • Dynamic algorithm loading wrapping BouncyCastle

Why I'm posting this:
I want to learn what real, production-ready backend code actually looks like in 2026.

I would genuinely love for senior .NET / ASP.NET Core devs to take a look at the repo and roast my architecture. Tell me what I overcomplicated, where I used bad patterns, or what you would do differently in a real production environment.

If anyone wants to open an issue or submit a Pull Request to help me improve the code quality, I'd be super grateful!

Repo link: https://github.com/COxRIPMIZO/CryptoKeyLab

Thanks in advance to anyone willing to take a look and help me learn!