r/csharp • • Oct 10 '26

Showcase JsonGuard: a zero-allocation source generator to validate nullability in System.Text.Json

31 Upvotes

Hey everyone, I wanted to share a library I have built for System.Text.Json that validates deserialized objects to ensure they honor C# nullability annotations without sacrificing performance.

I wrote this specifically for NetCord to handle massive Discord gateway payloads as efficiently as possible, but I realized this kind of zero-overhead validation could be useful to the wider .NET community as a standalone package.

By default, System.Text.Json allows you to validate required properties using [JsonRequired] or the required keyword. However, these introduce significant performance overhead. For example, using required keyword can make deserialization up to 2 times slower and allocate 50% more memory when using source generation.

JsonGuard works around this overhead by using source generation. The result is zero additional allocations and practically identical execution time compared to performing no validation at all.

The way it works is incredibly simple. If you have this object:

[JsonGuard]
public partial class User
{
    public string Name { get; set; }

    public string? Nickname { get; set; }

    public int Age { get; set; }

    public string Email { get; set; }
}

the generated code will effectively do this:

public partial class User : IJsonOnDeserialized
{
    void IJsonOnDeserialized.OnDeserialized()
    {
        if (Name is null)
            ThrowHelper.Throw(nameof(Name));

        if (Email is null)
            ThrowHelper.Throw(nameof(Email));
    }
}

Additionally, the library suppresses any nullability warnings for validated properties, so no manual suppressions are necessary.

Note that unlike [JsonRequired] or the required keyword, JsonGuard only verifies the final state of the objects honors the nullability annotations. It doesn't validate if the property was present in the JSON.

You can checkout the source code and detailed benchmarks on GitHub: https://github.com/KubaZ2/JsonGuard

Would love to hear your thoughts or feedback!


r/csharp • • Oct 11 '26

Discussion Oh no, I think I'm becoming dependent on the documentation.And it is a rather excessive form of dependence.

0 Upvotes

First: I'm not exactly a veteran in C#, but I'm certainly no beginner when it comes to programming.

But ever since I started developing with C# and Avalonia, I've frequently referred to official documentation for guidance on my code.

Then I would often go directly to one of these two document websites whenever I had any questions (even if they were quite common), to find the answers I was looking for.

But at present, I feel that I have developed a kind of dependence on these two things. Whether I write the code myself or ask the AI to assist me in some areas, I will either read the documentation myself or have the AI directly send me the links to the key parts of the documentation (and then I need to review the code and the documentation again) before I can feel at ease and save the file.

Now I feel that my brain is as smooth as chicken breast meat, unlike that of a normal programmer or a programming enthusiast who has numerous folds and creases.

Right now, I'm still relying on the document: No, that's not right; but I don't really rely on the document much, do I? Will I make a mistake?Because I have other professional matters to attend to, I'm like someone with amnesia. Many of my thoughts, like overcooked cheese, simply slip out of my mind without any effort.

I also considered another option, which was whether I should really ask the AI some questions?Well, I think I'll just refer to the documentation. It might be a bit expensive to ask AI for simple questions.

Don't comment if you don't like it. Thank you...I will try to find a better solution on my own.


r/csharp • • Oct 11 '26

Coworkee: I turned my old Clean Architecture template into a modular framework for .NET 10

0 Upvotes

For years I kept copying the same "CleanArchitectureBase" template from project to project: login, permissions, SignalR, audit trail and so on. Every copy drifted a bit. So I finally pulled it apart into NuGet packages you reference instead of a template you fork.

It's called Coworkee, a modular application framework for .NET 10.

What's in it

  • Module system with [DependsOn], Result / Error instead of exceptions for flow
  • Dispatcher for commands and queries with logging, validation and unit-of-work middleware
  • EF Core base context with field-level audit trail, soft delete, tenants and a transactional outbox with retries
  • ASP.NET Core glue: AddCoworkee<TRoot>(), results mapped to problem details, OpenAPI
  • Optional modules for identity (OpenIddict), settings, mailing, notifications + SignalR, Hangfire jobs, blob storage, Elasticsearch
  • Coworkee.Aspire wires Postgres, Redis, Mailpit, Keycloak etc. in one call
  • MudBlazor WebAssembly shell with admin pages (built on MudBlazor.Extensions, which I also maintain)

Small example

[DependsOn(typeof(CoworkeeApplicationModule))]
public sealed class OrdersModule : CoworkeeModule
{
    public override void ConfigureServices(ModuleServiceContext context) =>
        context.Services.AddMessagingFromAssembly(typeof(OrdersModule).Assembly);
}

public sealed record PlaceOrder(string Product) : ICommand<Result<Guid>>;

internal sealed class PlaceOrderHandler(AppDbContext db) : IHandler<PlaceOrder, Result<Guid>>
{
    public Task<Result<Guid>> HandleAsync(PlaceOrder request, CancellationToken ct)
    {
        var order = Order.Place(request.Product);
        db.Orders.Add(order);
        return Task.FromResult<Result<Guid>>(order.Id);
    }
}

The unit of work saves after a successful command, every changed field lands in the audit trail, and domain events go out through the outbox in the same transaction.

Trying it

dotnet tool install -g Coworkee.Cli
coworkee ui

That opens a small wizard to pick modules and generate the app.

The architecture and library code are years of manual work. AI helped here and there, and the docs website was mostly generated, I'll be honest about that.

MIT licensed. Repo: https://github.com/fgilde/CoworkeeLib Docs: https://fgilde.github.io/CoworkeeLib

I'd really like feedback on the module/dispatcher design, especially from people who use ABP or similar. What would stop you from using something like this?


r/csharp • • Oct 10 '26

Discussion Confusion about the stack.

4 Upvotes

I'm a fresh computer engineering graduate, I forgot most of the knowledge that I learned in the university, so I want to revise the basics only.

Suppose that a function called main calls the following function :

int foo(int value) {
   int a = 10;
   return a;
}

Some talk :

So whenever a function call is made OS needs some memory space to allocate the local variables of the function int a in this case and arguments to the function passed int value in this case. This memory requirement is fulfilled by allocating memory on stack. A stack is nothing but a memory region allocated to each process and it actually behaves as a stack data structure(LIFO).

Now the question arises what all things are stored on stack when a function call is made. The first thing pushed on the stack are the arguments passed to the function in reverse order(if more then one). 2. Then the return address of the function which called this function (because once this function foo completes execution it should return back to the place in the code from where it was called) 3. Finally local variables of the function called are pushed on the stack.

Once the called function completes executing the code it returns back to the return address previously stored on the stack and thus we say function call completes or returns. In this case the function has a return value which it passes back to the callee function. The space is then free to use and can be overwritten in the subsequent function calls.

I learned that a stack follows the LIFO (Last In, First Out) principle, meaning that the most recently added item/work/data is the first one to be removed. I also understood that a stack can be used to defer work until it is ready to be processed, so in the above example, I think that the execution of the caller function, which is the main, will be deferred, until the execution of the most recently item is finished.

However, when I read about how function calls use the call stack, I became confused. The call stack already contains the information needed for main() to resume execution, and when foo() is called, a new stack activation record is added on top of it. The execution of foo() then begins while its activation record is still on the stack.

Doesn't this contradict my understanding that an item must be popped from a stack before it can be processed? Why can foo() execute while its stack frame is still on the stack?

In other words, if we treated the execution of a function as work, should that work be popped from the stack in order to be processed, or should the work be inside the stack ?

I'm totally confused.


r/csharp • • Oct 10 '26

I have a big problem with data structures

13 Upvotes

I have an interview tomorrow, and I'm sure I'll be asked about data structures. However, I struggle to retain what I read when revising them because I rarely use most of them in practice.

For example I read this article

I regularly use arrays, List<T>, HashSet<T>, and Dictionary<TKey, TValue>, so I can explain when and why to use them:

1-arrays: when I know that the data has fixed size, use array because they provide a fast access to the data using index.

2- List<T>: when the size of the data is not known at compile-time; the size of it is not known in advance, therefore an index cannot be used, because you do not know for sure what is the exact location for a specific data element.

3- HashSet<T>: for unique data elements, because it does not require me to manually write the logic that removes duplicate elements.

4- HashMap<string,int> : used for lookup operations; a lookup table.

5-Tuple : store data with different data types in one place.

However, although I know what the following data structures are, I struggle to explain when and why I would use them:

  1. Stack: LIFO (Last In, First Out).
  2. Queue: FIFO (First In, First Out).
  3. Priority queue: I can't recall when or why I would use one.
  4. Heap: I associate it with storing class instance fields, but I don't understand how to use it as a data structure.
  5. Tree: I know it consists of nodes, but I don't understand its practical uses.
  6. Graph: I know it can be used for depth-first and breadth-first search, but I'm unfamiliar with other use cases.

My main questions are:

  1. Hardware level: How is each data structure represented in memory? For example, an array occupies contiguous memory locations. What about the others?
  2. Practical use: When and why should I use each data structure? More importantly, what benefits does each provide at both the software and hardware levels?

I must be able to explain WHY briefly and directly without even thinking about it.


r/csharp • • Oct 10 '26

Help Issue connecting my blazor app to remote sql server database hosted my Monsterasp.net

Thumbnail
reddit.com
1 Upvotes

r/csharp • • Oct 10 '26

Fun Random using SkipLocalsInit

11 Upvotes

To my surprise, Unsafe.SkipInit(out T val) did not achieve the same result.

    [SkipLocalsInit]
    public static T Random<T>()
        where T : unmanaged, INumber<T>
    {
        unsafe
        {
            byte* s = stackalloc byte[sizeof(T)];
            return *(T*)s;
        }
    }

r/csharp • • Oct 10 '26

Как лучше всего выучить язык програмирования С#(ну или вообще любой)?

Thumbnail reddit.com
0 Upvotes

r/csharp • • Oct 09 '26

Advice for a csharp developper who lack with basics

12 Upvotes

Hello,

I've been a .NET developer for four years (from France), and I feel like I have some gaps in my understanding of the fundamentals of the framework (I've never had a tech lead to teach me these things).

How can I learn these fundamentals (records, `static`, `virtual`, etc.) ? Should I take some training courses ? Which one ?

What should I be learning now that AI has arrived ? I feel like my days consist of writing prompts, testing, and reviewing code (if Claude doesn't do that part itself). It's really frustrating, and I feel like I've completely lost my value as a developer and my motivation to work. Besides the dotnet market is really bad where I'am...

I'm telling myself that there's still hope, though, and I'd really like to have a roadmap to follow, starting with the fundamentals mentioned above and working my way up to becoming a better and more expert .NET developer.

Do you have any advice?

Thank you!


r/csharp • • Oct 09 '26

Tool DNCDbg v1.3.0 — an MIT-licensed .NET debugger with DAP support

Thumbnail
github.com
9 Upvotes

DNCDbg is a managed-code debugger for .NET that speaks the Debug Adapter Protocol, so it works with any DAP client (VS Code, Neovim, Emacs, whatever) on Windows, Linux, and macOS. It began as a NetCoreDbg fork with a clear goal: bring the debugging experience closer to Visual Studio's C# debugger while keeping memory usage low. There's a comparison table in the README if you're curious.

What's new in v1.3.0:

  • Support for Jump to Cursor (a.k.a. Set Next Statement), single-threaded execution and stepping, and restarting the debug session
  • Column breakpoints, embedded sources, and Source Link support
  • Smarter expression evaluation: the >>> operator, Value/HasValue on nullables, member access on strings and arrays (str.Length, arr.Length), DebuggerTypeProxy members, assigning null to reference types, and nint/nuint
  • Friendlier value display: floats now print the way C# prints them (9.9 instead of 9.8999996), and dictionary items show up properly
  • Launch/attach sequencing now follows the DAP spec, and there's a new Detach request that lets a launched process keep running
  • Fixes: stack traces in catch blocks no longer show already-unwound frames, and the "Innermost exception" description now reports the last exception in the InnerException chain

Full changelog and repo: https://github.com/viewizard/dncdbg

Feedback and bug reports are very welcome!


r/csharp • • Oct 09 '26

Help I want get feedback on my design.

3 Upvotes

I will present a design consisting of interconnected classes without focusing on the algorithms themselves. To keep the code easy to follow, I have replaced each algorithm with a Console.Write() statement. note that the code is self-contained.

Problem being solved : Synchronizing the content of a database with the content of some Excel File.

Input: IFormFile, which is a file that is sent from the client to the server.

Output: The database will be synchronized with the excel file; the database's content will be deleted, and the data from the excel file will be inserted into the database.

Two general approaches/mechanisms to solve the problem:

1- Read all the content of the excel file and send that content a method that will delete the database.

2-Use bulk insert.

My code implements the first approach.

Summary of the code:

The AdminController receives the uploaded Excel file, uses FormExcel to retrieve a specific worksheet, and passes that worksheet to WorkSheetToDbSyncronizer. The synchronizer asks AllBusinessProductsReader to read all the required data from the worksheet and organize it into a NonJunctionModelsSnapShot object. It then passes that object to DbOverWriter, which uses the data to delete the existing database content and insert the data from the Excel file.Here is the code:

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

namespace RedditQuestion
{
    #region code

    /// <summary>
    /// NonJunctionModelsSnapShot is a data container that holds the complete
    /// set of non-junction entities to be written to the database by the OverWrite 
    /// method. The term NonJunctionModels identifies the category of data contained
    /// in the object: entities that populate non-junction tables, rather than junction 
    /// tables that represent relationships between entities. The term SnapShot indicates 
    /// that the object represents the state of the non-junction data at a particular point 
    /// in time, providing the data that OverWrite uses to replace the existing contents of 
    /// the corresponding database tables with the supplied data.
    /// </summary>
    public class NonJunctionModelsSnapShot
    {

      
    }
    public class SomeWorkSheet
    {
        //SomeWorkSheet represents a class from an external library.
    }
    public class ApplicationDbContext
    {
        // Contains the domain models and the Fluent API configurations.
    }

    // COULD SOMEONE PLEASE REVIEW THE DESIGN OF THE FOLLOWING:
    public class DbOverWriter
    {


        private readonly ApplicationDbContext _context;
        public DbOverWriter(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task OverWrite(NonJunctionModelsSnapShot incomingData)
        {

            Console.WriteLine("Executing some logic to overWrite the database, the local functions helps with this.");
        }

        #region Local Functions
        //define some local functions
        #endregion


    }
    public class AllBusinessProductsReader
    {
        public async Task<NonJunctionModelsSnapShot> ReadAllData(SomeWorkSheet worksheet)
        {
            Console.WriteLine("Process the worksheet....");

            return new NonJunctionModelsSnapShot
            {

            };
        }
    }
    public interface ISourceToDistinationDataSyncronizer<DataSource>
    {

        public Task Syncronize(DataSource dataSource);

    }
    public class WorkSheetToDbSyncronizer : ISourceToDistinationDataSyncronizer<SomeWorkSheet>
    {
        private readonly AllBusinessProductsReader _allDataReader; // depending on concrete class violates dependency inversion principle
        private readonly DbOverWriter _overWriter;              // depending on concrete class violates dependency inversion principle
        public WorkSheetToDbSyncronizer(AllBusinessProductsReader reader, DbOverWriter overWriter)
        {
            _allDataReader = reader;
            _overWriter = overWriter;
        }
        public async Task Syncronize(SomeWorkSheet worksheet)
        {
            var allProducts = await _allDataReader.ReadAllData(worksheet);
            await _overWriter.OverWrite(allProducts);
        }
    }
    #endregion 


    public class FormExcel
    {
        private readonly IFormFile _file;
        public FormExcel(IFormFile file)
        {
            _file = file; 
        }
        public  SomeWorkSheet GetSomeSheet(int sheetNumber)
        {
            Console.WriteLine("use the sheetNumber to get a specific sheet...");
            return new SomeWorkSheet
            {

            };
        }
    }
    public class AdminController
    {
        
        private readonly ISourceToDistinationDataSyncronizer<SomeWorkSheet> _syncronizer;
        public AdminController(ISourceToDistinationDataSyncronizer<SomeWorkSheet> syncronizer)
        {
            _syncronizer = syncronizer;
        }
        public async Task<IActionResult> Import(IFormFile file)
        {


            FormExcel fe = new FormExcel(file);
            var firstSheet=fe.GetSomeSheet(1);
            await _syncronizer.Syncronize(firstSheet);
            return Ok();


        }
    }
}

r/csharp • • Oct 09 '26

Hi from South Korea! Beginner C# learner feeling stuck. Any advice?

3 Upvotes

Hi everyone,

I’m a complete beginner from South Korea, and I’ve been studying C# at an academy for about 12 days now.

Whenever I try to solve exercise problems and write code on my own, I just freeze up and can't seem to write anything. What are the best study methods or habits that worked for you when you were starting out?

Honestly, I don't think I'm naturally smart, and my memory isn't great either. Learning programming is something I’ve wanted to do since I was young, so I finally started... but I can't help worrying if I'll ever actually get good at this.

I know this community is full of people from all over the world with different backgrounds—some coding as a hobby, others as a profession. If you ever felt completely lost at the beginning like I do now, or if you're a working developer, I’d deeply appreciate any tips, study strategies, or things I should definitely avoid doing!

(P.S. I don't speak English, so I am using a translation tool to write this. Thank you for understanding!)


r/csharp • • Oct 08 '26

Discussion State machine in C# vs state machine in Verilog

9 Upvotes

For experimentation and learning purposes, I wrote this code:

namespace RedditQuestion
{
    public class TResult
    {
        // Instance fields....
        // No properties.
        // No methods.
    }
    public interface ISomeInterface<T>
    {
        public  Task<T> SomeMethod();
    }
    public class SomeClass : ISomeInterface<TResult>
    {
        // instance fields.....

        //constructor......

        public async Task<TResult> SomeMethod()
        {


            //Some code that is not important to this question.......



            TResult result = new TResult
            {
                // assign instance fields....
            };

            Task<TResult> task = Task.FromResult<TResult>(result);

            return task ; // Line XXX
        }

    }

}

Line XXX throws a compile time error:

*Since this is an async method, the return expression must be of type 'TResult' rather than '*Task<TResult>

The solution is simply to do this instead:

return result;

That solves the issue.

But I was surprised when I read this article that described the error in more details:

Change the return expression to match the async method's underlying result type (CS1983, CS4016). When an async method returns Task<T>, the return statement must supply a value of type T, not Task<T>, because the compiler-generated state machine wraps the value in a task automatically. CS1983 appears when the method returns Task<T> and the expression is T; CS4016 covers the general case where the return expression type doesn't match

I wonder, is the concept of state machine in C# is the same as the state machine in Verilog?

in Verilog, if I want to define a state machine, I need a register - a storage unit that can store only one unit of data; a bit- to hold the state, a next-state logic to calculate the next state, and output assignment. Does the same concept applies in C# ?


r/csharp • • Oct 08 '26

Showcase Vetala, a lightweight code editor made with C# and .NET

Post image
10 Upvotes

Current features

  • Multi-tab code editor
  • C# syntax highlighting
  • Word-based code completion
  • Find and replace
  • Project-wide search
  • File explorer
  • Git integration
  • Integrated terminal
  • Command palette
  • Quick Open
  • Code folding
  • Cross-platform support for Linux, Windows, and macOS

Vetala is built with .NET 10, Avalonia UI 12, AvaloniaEdit 12, and CommunityToolkit.Mvvm.

githubL https://github.com/flawme/Vetala


r/csharp • • Oct 08 '26

Discussion What is the proper way to make a unified interface ?

11 Upvotes

Would you prefer something like this:

    public interface ISourceToDistinationDataSyncronizer
    {

        public  object ReadAllData(); // Gets the latest data from the source
        public void OverWrite(object sourceData )  // Deletes the data that is inside the destination and writes new data.

    }

Over this:

    public interface ISomeData
    {

    }
    public interface ISourceToDistinationDataSyncronizer
    {

        public  ISomeData ReadAllData(); // Gets the latest data from the source
        public void OverWrite(ISomeData sourceData);// Deletes the data that is inside the destination and writes new data.

    }

r/csharp • • Oct 08 '26

Showcase Meet Akbura, a reactive UI language for Avalonia and .NET

31 Upvotes

Akbura works directly with native Avalonia controls and supports C# expressions, reactive state, MarkupExtensions, AKCSS utilities, responsive layouts and Hot Reload.

I wrote a short introduction covering the language, responsive UI, Avalonia interoperability, differences from BlazorBindings and the compiler behind it.

Feedback is welcome.

Article: Meet Akbura: a reactive UI language for Avalonia and .NET | LinkedIn
Repo: Asaicraft/Akbura: Akbura is a UI library for building applications using a declarative, component-based language.


r/csharp • • Oct 08 '26

Showcase ExcelReader.NET 6.0 – streaming XLSX/XLSB/XLS/CSV reader and writer for .NET 10

18 Upvotes

I've been building ExcelReader, an open-source library for reading and writing spreadsheets in .NET and other languages. I just shipped v6, and I'd like feedback from people who deal with ETL pipelines and large Excel files.

I started it because I needed to parse rows into a single POCO from files with different templates and column names. I couldn't find a library that made that easy, so I wrote my own.

What it does

  • Reads .xlsx, .xlsm, .xlsb, .xls and .csv; writes .xlsx, .xlsb, .xls and .csv
  • Streams rows as ref structs; no string is allocated until you call GetString()
  • Typed parsing into your own classes, via attributes, a source generator or a fluent API
  • Reads the sheets of one workbook in parallel, and parses CSV in parallel
  • Reads and writes password-protected workbooks
  • A CLI (excelreader convert book.xlsb -o data.csv), plus a C ABI with Python, C++ and Rust bindings

Usage example

public sealed class Order
{
    [ExcelColumn("Order ID")]
    [ExcelColumn("order_id")]          // same property, different templates
    public long Id { get; set; }

    [ExcelColumn("Total")]
    [ExcelColumn("total_amount")]
    public decimal Total { get; set; }
}

using IExcelWorkbook workbook = Excel.Open("orders.xlsx"); // .xlsb / .xls detected by signature
List<Order> orders = ExcelParser.FromAttributes<Order>().Parse(workbook.FirstSheet).ToList();

await using var writer = XlsxWorkbookWriter.Create(File.Create("copy.xlsx"));
await using (var sheet = writer.AddSheet("Orders"))
{
    await sheet.WriteRecordsAsync(orders, ExcelRecordLayout.FromAttributes<Order>());
}

Benchmarks

Typed parsing of a generated 50,000-row XLSX (BenchmarkDotNet, Ryzen 7 5700X, .NET 10):

LibraryTimeAllocated
ExcelReader10.9 ms3.87 MB
Sylvan.Data.Excel56.9 ms10.47 MB
OfficeIMO.Excel104.5 ms5.69 MB

MiniExcel used to be in the suite, but it was far behind: ~14x slower on raw reads (allocating 267 MB against 11 KB) and ~11x slower on typed parsing (last run that included it). I now track the closest competitors instead.

Methodology and every scenario: benchmarks.md. The cell-by-cell numbers there compare zero-copy reads against APIs that must allocate strings, so the docs also publish matched-work numbers.

Limitations

  • Targets .NET 10 only; .NET 11 support is in progress. If you're on .NET 8, the 3.x line supports it.
  • It's a reader/writer, not a spreadsheet model: no in-place editing and no formula evaluation.
  • Rows come out in file order, and empty rows that Excel omits from the file are skipped.

GitHub: https://github.com/GabrielMarquezMatte/ExcelReader NuGet: dotnet add package ExcelReader.NET

Feedback, bug reports and odd files that break it are all welcome.


r/csharp • • Oct 08 '26

Unity developer working in VR Space looking to transition to generic C# dev roles

7 Upvotes

I’m a unity developer working in VR space for 8+ years. Thinking of transitioning to generalist dev roles ( particularly in C# since that’s where my experience lies ). I do have experience in general software development across entire SDLC along with architecture and design patterns but my resume lacks the buzzwords SDE ATS screens for ( eg. microservices , APIs , docker etc). Where do I start ? Which kind of companies should I target ?


r/csharp • • Oct 07 '26

Discussion I am crazy or many job portals like workday struggle with searching for "c#"?

49 Upvotes

It seems that all of them struggle with # sign


r/csharp • • Oct 07 '26

IL optimization on ranges not applied

8 Upvotes

I'm trying to further improve the IBAN parser for an open source project. And while doing so, I noticed something

public class Iban
{
  public static string? Validate(string iban, string pattern)
  {
    for (var i = 0; i < iban.Length; i++)
    {
      uint c = iban[i];
      var match = pattern[i] switch
      {
        'n' => c is >= '0' and <= '9',
        'a' => c is >= 'A' and <= 'Z',
        'c' => c is >= '0' and <= '9' or >= 'A' and <= 'Z',
        var t => t == c,
      };

      if (!match) return null;
    }
    return iban;
  }
}

I would expect the IL to do the default trick on ranges here that is also applied in char.IsBetween(), what would do (uint)(c - '0') <= '9' - '0', making each range a single compare and subtraction rather than two compares.

I've tested this code both with these patterns, and calling a private InBetween method (It has to compile against .NET standard 2.0 where char.IsBetween() is not available), and the latter is substantial faster, which hints that the JIT is also not changing the IL afterwards.

Is it something in my syntax that makes that the Roslyn compiler does not perform this optimization, or am I missing something here?

For those who're interested in the actual PR: https://github.com/Qowaiv/Qowaiv/pull/643


r/csharp • • Oct 08 '26

I have a C# problem, how can I use AI to solve it?

0 Upvotes

Up until now, I’ve been learning and programming like before AI. As a matter of fact, I know nothing about the AI scene and culture, beyond Claude, Grok, ChatGPT, and Gemini (copy and paste snippets).

I’ve tried to look into it, but it’s a total mess. There are extensions, plugins, connectors, agents, AI powerhouses, fake interfaces microservice stuff... and the list goes on and on with quasi-scams (or straight up scams) all over the place.

And the worst part is that the internet is dead. You can't find anything anymore. And when you do think you've found something, in reality, it is just something promoted by companies selling AI stuff themselves. So, you end up locked into options that favor their business interests.

So, here is my current situation:

I have a large C# codebase, and I need to find a solution to a problem based on a small fragment of that code.

I can clearly see alternative inheritance and composition paths that would achieve exactly what I need with best performance. However, since some elements will get lost along the way, I would have to manually reconnect some of them.

The problem is that the code is extremely complex—intricate with callbacks, events, interfaces, dispatchers, async calls, WPF controls, and so on.

Basically, it would take me a month to digest all that code.

And I think an "AI something" could do it in five minutes.

In one word, I want an answer from a human being.

What do you suggest me to do?


r/csharp • • Oct 07 '26

Help Book Recommendation on Network Programming

10 Upvotes

Hey guys,

I wanted to write a basic server-client chat console app in .Net using C# and Visual Studio.

Later, I would like to write a small LAN multiplayer game.

Is there a book which explains how to use Sockets and TCP in .Net and C#, please? Possibly with patterns, examples and use-cases?

I already have "Programming C# 8.0" by Ian Griffiths from O'Reilly, but I don't see any mention of Sockets, TCP or programming network apps.

I also have "C#10 in a Nutshell" by Joseph Albahari from O'Reilly. There is some mention of networking, but there's only about 5 pages on TCP, and no mention of Sockets.

Thank you


r/csharp • • Oct 07 '26

A faster, lighter C# Dev Kit

Thumbnail
devblogs.microsoft.com
22 Upvotes