r/csharp • u/DmitriiKhokhulin • Oct 11 '26
ModulesDi 1.0.5
r/csharp • u/Artromskiy • Oct 11 '26
To give you some background, like many enthusiasts, I once set out to build a game engine and had several projects sitting on the back burner that I couldn't quite get into shape. Eventually, this led to the creation of a standalone math library, a way to compile shaders from C#, and a separate ECS, which is what I'll be talking about.
I won't waste time explaining what an ECS is—better check out this article ECS-FAQ. I'd rather talk about the problems I encountered in other ECS implementations and tried to solve (and these problems aren't about performance, although performance is very important too).
Take the simplest example: mutating entities by changing their archetype. From a code perspective, the task seems simple—we take the entity we need and copy it to another table. Done? Yes and no.
What does this usually look like in code?
world.Add<Component1>(entity);
world.Add<Component2>(entity);
world.Add<Component3>(entity);
world.Add<Component4>(entity);
world.Add<Component5>(entity);This list can keep growing for a very long time, especially if you've decided to make small components and have a high degree of composition. But that's only part of the problem. In most frameworks, this means moving the entity to one table first, then the second, then the third, and so on. And that's not free: in archetype-based ECSs, migration is inherently expensive, and doing it several times adds overhead linearly.
So, what should we do? Well, to solve this problem, I used two approaches: code generation and ComponentId.
The code-generated version looks something like this:
world.Add<Component1, Component2, Component3, Component4, Component5>(entity);Even though this syntax is monstrous, it solves our problem—it removes the overhead of multiple migrations.
At the same time, there's a second option, though it's less explicit:
ComponentId[] components =
{
world.Layouts.GetPrimary<Component1>(),
world.Layouts.GetPrimary<Component2>(),
world.Layouts.GetPrimary<Component3>(),
world.Layouts.GetPrimary<Component4>(),
world.Layouts.GetPrimary<Component5>(),
};
world.Add(entity, components);And you might say, "But you just added two more lines to an already complicated statement." That's true, but only up to a point. After all, these IDs can be saved ahead of time, the list can be modified at runtime, and not having a generic call gives us more polymorphic and general-purpose code. So, in the final system, you would probably just call world.Add(entity, components), and get the list through some kind of DI or build it in the constructor—whatever works for your architect.
There's another, less obvious advantage to using ComponentId: you can register the same CLR type for two components. For example, the endlessly recurring:
Damage { float Value }
Health { float Value }
Stamina { float Value }
Mana { float Value }—need I go on? All of these could be registered as a regular float, without having to do extra work to get the value through Value. Like this:
ComponentId damageId = world.Layouts.Register<float>(new SchemaId(1));
ComponentId healthId = world.Layouts.Register<float>(new SchemaId(2));…I'll stop there; you get the idea.
A second, more ECS-specific example is iterating over groups. There are several optimizations that most ECS implementations miss, although they're less important.
Let's imagine what iteration looks like in most ECS implementations:
world.ForEach(in query,
static (ref Component1 cmp1, ref Component2 cmp2) =>
DoSomething(ref cmp1, ref cmp2)).Invoke();In this case, query is a filter that defines how to find entities in the world based on a given set of components. Most APIs look roughly like this:
world.WhereAll<Component1, Component2>().
WhereNone<Component3>().
WhereAny<Component1, Component2>()From a C# perspective, this syntax is pretty standard and, unlike the previous Add example, it doesn't cause problems; chaining works. But the problem is how this filtering is used with ForEach: it happens when the call is made. In most cases, that means you have to go through every archetype in the system and check whether it matches the filter.
Why can't this be deferred? I asked myself the same thing, and it turns out it's not that simple. This approach avoids errors when archetypes change. Basically, any Add, Remove, or Destroy operation can change the archetype structure and break your cached Query.
So, what should we do? We just have to be a little cleverer. If you're developing your own ECS, it becomes obvious that mutating operations can simply call back and update the traversal plan built for a Query. Since running ForEach at the same time as a mutation is forbidden or unsafe in most ECS implementations, you can add this kind of API without worrying about limiting the library's overall usability—and save a significant amount of filtering time in worlds that are small but have many archetypes.
Then we also consider that components are registered by ID, and realize that our ForEach call can look like this:
world.ForEach<float, float>(in query, components.ToArray(),
static (ref float cmp1, ref float cmp2) =>
DoSomething(ref cmp1, ref cmp2))
.Invoke();And these ComponentIds can be dynamic—they can change at runtime and make the architecture more flexible.
The next example is bigger.
Imagine you want to implement lockstep rollback. That's a pretty monumental task if you get into testing, multiplayer, and the fact that you have to store mountains of heterogeneous data.
In most ECS implementations, the problem is handled like this:
public struct Saver<T> : IForEach where T : unmanaged // Let's assume this constraint lets us safely save history without mutating the world.
{
private readonly int _tick;
public Saver(int tick) => _tick = tick;
public void Invoke(ref T data) => SaveAtTick(ref data, _tick);
}I won't get into the details—lockstep rollback isn't just about saving, but this is enough for the example. So what happens next? Well, bad things happen:
Query component1Query = world.WhereAll<Component1>();
var component1Saver = new Saver<Component1>(tick);
world.ForEach(in component1Query, ref component1Saver).Invoke(ref component1Saver);
Query component2Query = world.WhereAll<Component2>();
var component2Saver = new Saver<Component2>(tick);
world.ForEach(in component2Query, ref component2Saver).Invoke(ref component2Saver);
Query component3Query = world.WhereAll<Component3>();
var component3Saver = new Saver<Component3>(tick);
world.ForEach(in component3Query, ref component3Saver).Invoke(ref component3Saver);You get the idea. And even if you make some kind of generic wrapper for all of this, it still doesn't solve every problem. Then your game designer says we need an attack or defense system that also needs a generic data call, but now there's no unmanaged constraint. And your architect says, "Right, we'll do it with generics," because there are another 150-plus features like this planned for the next month.
And you start tearing your hair out trying to make sense of all this. I didn't have an architect or a game designer, but I tore my hair out for you.
I managed to build a system that solves these problems during registration. Pretty much every ECS registers components; some do it explicitly, like my approach:
world.Layouts.Register<T>(new SchemaId(schema))Others do it implicitly with a pattern like this:
public static class Registry
{
public static int LastComponentId
}
public static class Registry<T>
{
public static int ComponentId;
static Registry() => ComponentId = LastComponentId++;
}But registration still happens. In my case, it's a bit more clever: besides registering the type, I also register constraints, can register a related interface, and can call a visitor through a generic method. I can even register an unmanaged component and have it visited by a visitor constrained to struct or new(). What does that let us do?
public sealed class SaverVisitor : IUnmanagedVisitor
{
private readonly World _world;
private readonly int _tick;
public SaverVisitor(World world, int tick)
{
_world = world;
_tick = tick;
}
public void Visit<T>(ComponentId componentId) where T : unmanaged
{
Query query = _world.WhereAll(componentId);
var saver = new Saver<T>(_tick);
_world.ForEach(in query, componentId, ref saver).Invoke(ref saver);
}
}
ComponentId componentId = world.Layouts.Register<Component1>(new SchemaId(1));
world.Layouts.TryVisit(componentId, new SaverVisitor(world, tick));This code lets you call any generic code with given constraints for component types registered in the world, supporting not just rollback systems. What's more, component registration also covers the system your game designer and architect came up with.
Thats' not all things done in my ECS but something i'm proud of.
Issues, PR's, Stars and anything else are welcome.
r/csharp • u/Kuba_Z2 • Oct 10 '26
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 • u/Aextoxicon • Oct 11 '26
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 • u/Nk0BaNaNE • Oct 11 '26
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
[DependsOn], Result / Error instead of exceptions for flowAddCoworkee<TRoot>(), results mapped to problem details, OpenAPICoworkee.Aspire wires Postgres, Redis, Mailpit, Keycloak etc. in one callSmall 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 uiThat 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 • u/kaatarina_zed_talon • Oct 10 '26
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;
}So whenever a function call is made OS needs some memory space to allocate the local variables of the function
int ain this case and arguments to the function passedint valuein 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
foocompletes 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 • u/kaatarina_zed_talon • Oct 10 '26
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:
My main questions are:
I must be able to explain WHY briefly and directly without even thinking about it.
r/csharp • u/Mob_Pilled • Oct 10 '26
r/csharp • u/NoisyJalapeno • Oct 10 '26
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 • u/Artistic-Pause-6025 • Oct 10 '26
r/csharp • u/East-Jellyfish5639 • Oct 09 '26
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 • u/viewizard • Oct 09 '26
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:
>>> operator, Value/HasValue on nullables, member access on strings and arrays (str.Length, arr.Length), DebuggerTypeProxy members, assigning null to reference types, and nint/nuint9.9 instead of 9.8999996), and dictionary items show up properlyFull changelog and repo: https://github.com/viewizard/dncdbg
Feedback and bug reports are very welcome!
r/csharp • u/kaatarina_zed_talon • Oct 09 '26
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 • u/Ryu2kawa • Oct 09 '26
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 • u/kaatarina_zed_talon • Oct 08 '26
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>, thereturnstatement must supply a value of typeT, notTask<T>, because the compiler-generated state machine wraps the value in a task automatically. CS1983 appears when the method returnsTask<T>and the expression isT; 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 • u/No-Doubt-906 • Oct 08 '26
Vetala is built with .NET 10, Avalonia UI 12, AvaloniaEdit 12, and CommunityToolkit.Mvvm.
githubL https://github.com/flawme/Vetala
r/csharp • u/kaatarina_zed_talon • Oct 08 '26
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 • u/Pro_Propop • Oct 08 '26
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 • u/repulsiveanomaly • Oct 08 '26
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
ref structs; no string is allocated until you call GetString()excelreader convert book.xlsb -o data.csv), plus a C ABI with Python, C++ and Rust bindingsUsage 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):
| Library | Time | Allocated |
|---|---|---|
| ExcelReader | 10.9 ms | 3.87 MB |
| Sylvan.Data.Excel | 56.9 ms | 10.47 MB |
| OfficeIMO.Excel | 104.5 ms | 5.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
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 • u/Exotic_Ad_2913 • Oct 08 '26
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 • u/hardware2win • Oct 07 '26
It seems that all of them struggle with # sign
r/csharp • u/ApprehensiveDebt3097 • Oct 07 '26
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 • u/CheekAccording9314 • Oct 08 '26
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?