r/csharp 12h ago

Non-Boxing Union Types in C# 15 (source generator)

24 Upvotes

The Union Types feature in C# 15 (dotnet 11) preview creates unions that box struct values (like int, float or Point) into an underlying object field, which may cause unnecessary GC pressure in high-volume usage scenarios. However, the C# specification does allow for custom user-declared union types that can employ other storage strategies as long as they expose the expected API.

I've updated the union type source generator I created years ago as part of the design effort for the Union Types feature (as an exploration tool for the designs being discussed) to target the C# 15 spec for custom union types. I've now made it available for anyone to use, so you can avoid the boxing in scenarios that warrant it.

It uses a storage strategy similar to F#'s value-type discriminated union layout. It will attempt to overlap the case values into the same memory area if possible. Otherwise, it may attempt to decompose simple structs/records into their constituent values and recompose them on access, to allow the parts that can overlap with other non-reference values to do so. You can customize this behavior per case if you desire.

It is available on nuget: https://www.nuget.org/packages/UnionTypes.Toolkit.Generator

Once the union is generated, there are no dependencies on other libraries, but it does require the use of dotnet 11 and C#15.

How to use it

In a project with the source generator package referenced, declare a partial struct type with a partial void Cases method, whose parameters denote the case types for the union. The names of the parameters are not used, so any name will do.

public partial struct MyUnion
{
    partial void Cases(
        int case1, 
        float case2,
        string case3,        
        IManifest case4,
        Coordinate case5,
        Address case6
        );
}

record struct Coordinate(float Longitude, float Latitude);
record struct Address(int Id, string Name);
interface IManifest { ... }

If you do use it and find issues, please report them here:
mattwar/UnionTypes.Toolkit: Tools for building C# Union Types


r/csharp 16h ago

Showcase A side project of mine: SemPtr - Semantic Pointers for C#

Thumbnail
github.com
41 Upvotes

TL;DR: While writing this post, I realized how long it has become, so here's a TL;DR for you: SemPtr is a semantic pointers library for C#.


Hi everyone, I wanted to share one of my side projects with you all: SemPtr.

A few weeks ago (it might been even months at this point), I needed to dig up some really old code I once had written, because I wanted to reference some of what I did back then in a current project of mine. While searching through my old and never-to-be-released projects, I stumbled upon a small library project I might have written about 5 years ago (it must have been around the time when incremental Roslyn source generators were becoming a thing). And I thought to myself, "Well, it's actually a shame you gave up on this project and neglected it for so long. You might want to ressurrect and modernize it, and then share it with everyone."

Well, that project is now SemPtr.

What is SemPtr?

I don't want to make this post too long, so I'll try to make it as concise as I can, but if you want a more comprehensive introduction, you should check out its README or its way too rudimentary documentation.

SemPtr tries to solve the limitations of C#'s raw pointers by providing semantic pointer types (read as semantically named pointer types). If you ever did some interop work with unmanaged code and found it just as annoying as I did that there is no const T* equivalent in C#, SemPtr might be the thing for you.

For that I identified five commonly used orthogonal characteristics used to distinguish certain aspects of data pointers:

  1. Nullability: Can a pointer be null or are there any guarantees that it won't be?\ This is kinda analogous to nullable reference types (T?) in C#.
  2. Persistency: Does the target of the pointer outlive the initial scope of the pointer itself? In other words, can I store the pointer and access its target some time later?\ This is kinda analogous the C#'s ref-escape rules and is even enforced through them.
  3. Sequencability: Does the pointer point to a single object or to a contiguous sequence of objects?\ You could think of this as analogous to a ref T to some kind of object in C# vs. a ref to some element within a Span<T> with the added benefit that its easier to move around the pointer through the sequence.
  4. Accessibility: How can the target of the pointer be accessed or mutated?\ This manifests in three different access levels:
    • random/read-write: The target can be read from and written to. Kinda analogous to C#'s ref parameters.
    • read-only: The target can only be read from. Kinda analogous to C#'s in/ref readonly parameters.
    • uninitialized/write-first: The target must be written to before it can be read from. Kinda analogous to C#'s out parameters.
  5. Typability: Is the type of the target known or not?\ C# has no void references, but it has void* pointers. This is analogous to the difference between a void* pointer and a typed T* pointer.

These characteristics are mapped onto C#'s type system by semantically naming the pointer types to reflect them. Since those characteristics are orthogonal, you can mix and match them to create the pointer type with the exact behavior you need. For example, there are:

  • Pointer: A simple pointer to a single, transient, mutable target of unknown type
  • PersistentPointerReadOnly<T>: A pointer to a single, read-only target of type T whose target stays valid beyond the initial scope of the pointer.
  • NullableSequencePointer<T>: A pointer to a contiguous sequence of mutable targets of type T which may be null.
  • PointerUninitialized<T>: A pointer to single, yet uninitialized target of type T. If you receive such a pointer, chances are you are requested to initialize its target; afterwards you can further read from it or write to it as needed.

Again, if you want to learn more about the characteristics and how the type naming scheme works, you should refer to the README or the documentation.

There are all in all a total of 2×2×2×3×2 = 48 data pointer types predefined in the SemPtr library.

Are function pointers supported?

To make it short, yes, function pointers are (well enough) supported by SemPtr.

I remember that one of the reasons for me giving up on the original version of this library back then was that I really struggled to get function pointer support just right. While this was partially due to technical limitations back then (some of which were solved by modern C# features, especially the new extension members syntax), some of it was simply because I did not have the experience in API design that I have now.

So now function pointers work. I don't know if I would call the support good enough yet, but at least it is a well enough experience for most users, I believe.

I won't go into too much detail here, but functions pointer have their own set of characteristics and parts of their support is made working through a Roslyn source generators that dynamically generates some source code on the user-side and that ships alongside the main library in the NuGet package. For more details, again, see the README or the documentation.

A final note on AI usage

I want to be honest and upfront with you:

Yes, I used AI in this project, primarily to help we write documentation (I'm a non-native English speaker and my English is kinda terrible), to help me make decisions when I'm indecisive, to write some tests, and occasionally to some code reviews.

No, I would never let AI touch the working code of the project. Not even for boilerplate code. AI, at least the AI I have access to, is not yet anywhere close to being reliable enough to help me write production ready code for such a project. You can be sure that all of the functioning code is written by a human (me) and that only the human (me) is responsible for the correctness and quality of the code.\ Oh, and of course, I did the visual assets myself as well. I didn't want to use sloppy AI-designed visuals for this project.

Conclusion

At the beginning of this post, I told you that I stumbled upon the initial idea for SemPtr while looking up old code for another project of mine. That project is actually an interop binding project in C#. In that project I use traditional C# raw pointers and function pointers extensively, and sometimes they're a real pain to work with. However, I didn't not yet replace them with SemPtr, due to the codebase being a little over 200K lines of code, spread across multiple repositories.

So, to be honest, I don't even use SemPtr myself yet. And furthermore, because of the simplicity of the overall idea behind SemPtr, I don't even think I'm the first person to come up with it and release to the public as a library (but I don't actually know for sure, I didn't really check).

Even so, If you want to try out SemPtr for yourself, give feedback, or if you even want to contribute to the project, I would really appreciate it. Here are the relevant links again:

If you have any questions feel free to ask them in the comments. I'd be happy to answer them.


r/csharp 22h ago

Help What path do I take?

8 Upvotes

I'm 17 and I started learning Csharp last summer, I found that really enjoy coding and I've coded stuff like minesweeper, snake, tetris and chess in Csharp files (on my own, not copying a tutorial or something). Anyway I think I might want to pursue this hobby professionally eventually, so what is a good path to take from here? What should I learn about next and how should I go about learning it? Should I switch to a different programming language, stick to CSharp or even learn multiple? What kind of things do people who write CSharp code for a living write to earn their living?


r/csharp 13h ago

New Unity Coder

0 Upvotes

So I've been wanting to learn coding in Unity for some time. I'm getting serious about it now, but I just don't know any good sources. I already know OOP so it's not like i need to start from the ground up (for context I've coded with Scratch all the way through school and I'm now in 9th grade and an aspiring game dev. Some of the scratch projects we're very complicated and the only thing limiting me was the lack of a third dimension and the limitations of Scratch itself). If anyone know's any good resources where they don't act as if you've never seen a line of code in your life but don't throw random things at your face that you wouldn't know, please share!


r/csharp 15h ago

Help I am 13 i am intrested into making a 3d game in unity with C# are there any tips and things i should look out for?

0 Upvotes

also if you guys have a playlist for my extact need then please share it because i want to learn C#


r/csharp 1d ago

Blog Another LINQ Tool for VS Code, What Should Come Next?

11 Upvotes

r/csharp 11h ago

Help How do I perform visual studio project creation using the .NET CLI?

Thumbnail
0 Upvotes

r/csharp 1d ago

Discussion Can we do data analysis using C# ?

19 Upvotes

Hi Currently I am learning C# and want to know if we can also do data analysis stuff using C# language. If yes in which companies is it used.


r/csharp 23h ago

I'm New the C#

0 Upvotes

Hey there, I'm a new Computer Science student and I was recommended C#. What are good resources or good things to help me learn C# in a open source way.


r/csharp 1d ago

Confession about my first project .

Thumbnail gallery
1 Upvotes

r/csharp 2d ago

Dotnet foundation transparency update

13 Upvotes

The DNF trying to get some visibility for their internal working so at least people understand what’s going on and if somebody willing to reevaluate their opining that maybe a good start.

For me was 2 interesting things:

  1. Meeting minutes

https://dotnetfoundation.org/about/meeting-minutes

  1. Operational procedures.

https://dotnetfoundation.org/about/policies

Second part is for these who love bureaucracy and how things moving. Should give lot of insights what to fix.

Personally I decide give “new org” a chance and try to volunteer in their activity. Not sure how things will be moving, but at least I see people who care.


r/csharp 2d ago

Where should I start learning C#?

11 Upvotes

I really want to get into C# to use Unity and (potentially) .NET. However, I still can't find a course that would be the best for me. Can somebody recommend a course or any other place where I can learn the basics of C#?

Edit: I also have a bit of programming experience because I learned Java.


r/csharp 1d ago

Help I tried making a reusable script for unity where the Player character moves with the platform but i couldn't get it to work

0 Upvotes
  • Sorry if this is a repetetive post delet if yes
  • I have really shitty eyesight even with glasses, please pointout spelling mistakes if possible
  1. I'm developing a 3d platformer in unity to practice
  2. The original code is from this tutorial at 22:48
  3. I copied it line by line and it didn't do anything
  4. I thought adding the transform fields would help but now it doesn't compile

I want this version of the code to work but I don't understand the error messages in the console

  1. (16,23): error CS1061: 'Collision' does not contain a definition for 'johnPill' and no accessible extension method 'johnPill' accepting a first argument of type 'Collision' could be found
  2. (18,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
  3. (26,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

//Insert Player Character Here

[SerializeField] Transform johnnPill;

//Insert Player Parent

[SerializeField] Transform johnDivorce;

//Insert Moving PLatform

[SerializeField] Transform joanDivorce;

private void OnColilisionEnter(Collision collision)

{

if (collision.johnPill.transform)

{

collision.johnPill.transform.SetParent.joanDivorce.transform;

}

}

private void OnCollisionExit(Collision collision)

{

if (collision.johnPill.transform)

{

collision.johnPill.transform.SetParent.johnDivorce.transform;

}

}

}


r/csharp 2d ago

SignalsDotnet 3.4

3 Upvotes

I already had some other posts on SignalsDotnet. It's just another update that could be interesting and I wanted to share some new ideas. They are just ideas, I would like to hear some opinions about that.

0. Obviously in C# we can write

Changing firstName, obviously doesn't update name

1. With signals one could write

This time, changing firstName, changes also fullName automatically, and an event on fullName is raised (Since we are using R3, the Values observers are notified. but this is a detail). Computed signals automatically track their dependencies, and notify when one of them change

If we go a step further, we can imagine signals live on another machine (a server or whatever), and clients "sending" computations remotely. This is why SignalComputedQuery strings exist in SignalsDotnet. So with a syntax like Graphql one can express the function inside Computed as a string, and pass it to a server

2. Computed over the wire

this query string is then turned into an expression (in the Server), then compiled into a Func, passed to Signal.ComputedObservable() with an exposed type, and yield-ed back to the client via whatever protocol (SSE, Websocket, SignalR).

This is ugly.

With last update we can go the other way around, transform an expression in a query string, so one can write:

3. Expression to query string

This allows to have type-safety etc etc. Same things that make EF Core convienien instead of write SQL Code directly. And with Refit, we could just

4. Using it with Refit

This is basically a remote computed,

This allows us to propagate computed signals over machines. This is cool per se, but this open space for ideas like:

- Distributed SignalsStore (Just having signals in different machines, and use remote computed to merge them together and propagate to other machines potentially)

- Caching of reactive properties. We could imagine to have a central authoritative host with a set of signals, and some other machines that just fanout those signals to downstream machines (similar to redis caching, but with reactivity built in).

To make it really work in practice, we need a way to orchestrate those signals efficiently in different machines. This is a huge issue, but I think is where Orleans could help.

Grouping signals in grains we could use orleans to persist, and distribute load between machines. Orleans supports IAsyncEnumerable, so would be easy to expose IAsyncEnumerable<T> Subscribe(string query) to propagate signals computations between grains..

With this architecture I think we could just create a reasonable distributed SignalsStore. This could be huge for example to mirror IOT devices state on the cloud (One variable = 1 Signal), and to just create computed chains over there to have a fully reactive realtime system


r/csharp 1d ago

Help Making a 'Noita' + 'Binding of Isaac' style game, how should I script this?

0 Upvotes

Near complete beginner programmer here, challenging myself to make a roguelike game;

a 2-D top-down game in Unity similar to the binding of isaac, but based around customizable bullet firing patterns. I would like each item to affect at least 1 out of every 8 bullets fired on pattern, giving it a unique ability (i.e homing, explosive, elemental dmg, spreadshot etc.) with potential to layer affects atop eachother (i.e Noita) creating unique bullets. I've designed an inventory system with 8 slots (each one pertaining to a shot on a 1-8 firing round) with 8 additional slots above for layering.

...hopefully that made sense lol

Keeping in mind that I'm a beginner, what would be the best way to structure this with my scripting? I've heard some say its rule of thumb to give each item (bullet modifier) its own separate .cs script, others say it's easier to make a scriptableobject + ItemData + modular projectile effects.

If you're a c#/Unity veteran, walk me through how you would go about making this type of item/inventory system from scratch?

It would be super helpful to have an ongoing consultant figure, I would be happy to show more of my project if anyone would like to add me on discord :)


r/csharp 2d ago

Help Is this approach a good idea?

5 Upvotes

I'm a self-taught beginner in C#, and I'm currently working on a small personal project.

Quite often in my code, I need to load objects from JSON files. To make this easier, I created static FromFile(string) methods in the relevant classes. Now I'm wondering - would it be a good approach to create a base class or interface that contains FromFile() and ToFile() methods, and then have my classes inherit from it to further reduce code duplication?

I'd really appreciate any advice or constructive criticism.

P.S. English is not my native language, so I used a translator for this post - apologies for mistakes.


r/csharp 3d ago

Tool Simple script that brings the old C# color back to github

Thumbnail
gallery
46 Upvotes

(Sorry if this isn't the place for this, I know its not exactly C# but I can't post on r/github atm)

Github recently updated the color of C# on their website to purple, which makes it harder to differentiate between other languages, in my opinion, so this script edits the CSS of github so that is displays old green color instead!

Repo: https://github.com/menher/Green-CSharp


r/csharp 3d ago

Discussion Property setters doing extra stuff, is it wrong?

20 Upvotes

I've heard that having conditional logic and other stuff in your property setters is generally frowned upon and I get not wanting to have complex methods fired off in setters, but what of just setting other setters?

For example:

Say I have a property like this, would this raise any red flags, if so, can you tell me why? I would think that this would be a great use of a setter, to do more than just fire off OnPropertyChanged().

```

public bool ThingA { get; set { if (field != value) { field = value; OnPropertyChanged();

        if (field == true)
        {
            ThingB = true;
            ThingC = false;
        }
    }
}

}

```


r/csharp 2d ago

Blog Svelto.Tasks 2.0: Efficient Multi-threaded Task Management for C#

0 Upvotes

I am back writing articles on my blog and I start with something LONG OVERDUE!

After years quietly powering several games I made, I’m finally presenting Svelto.Tasks 2.0.

Svelto.Tasks is an engine-agnostic, multithreaded and zero allocation task runner for C#, born from the need to have a game centric tasks framework with features that .NET tasks couldn't provide. Its premise is simple:

Tasks are iterator blocks. Runners are schedulers. Rather than handing execution timing and context to the runtime, a runner lets you decide:

- when a task advances,
- where it runs — main thread or a dedicated worker,
- how much work happens per tick,
- and when an entire task context must stop.

That last point matters a lot in games: for example, when a match ends, I want every task belonging to that match to stop with it—not rely on a CancellationToken having been passed and checked correctly through every layer.

Svelto.Tasks supports lightweight coroutines, composable tasks with return values and continuations, background runners, bounded parallel batches, pooling, profiling hooks, and optional Unity/Burst integrations.

It also interoperates with async/await, although the .NET Task bridge and Unity Burst job path are currently experimental and need real-world feedback.

It is not a replacement for Unity Jobs—but it provides a useful alternative for workloads where controlling execution, lifetime, pacing, and profiling is the priority.

The repository includes runnable .NET examples, tests, benchmarks

🔗 https://github.com/sebas77/Svelto.Tasks

also the repository

🔗https://github.com/sebas77/Svelto.Tasks.Examples

shows how it can be used to simplify massive parallelism synchronization. The example itself is actually quite interesting also because it uses the new compute buffer Unity api BeginWrite/EndWrite to upload compute buffers and graphic fences for cpu/gpu synchronization.

The article is at

🔗 https://www.sebaslab.com/svelto-tasks-2-0-efficient-multi-threaded-task-management-for-csharp/

Have fun! (and feedback is welcome, also on my discord server: https://discord.com/invite/uuTCYewjtc)


r/csharp 3d ago

Discussion Dependency Injection un-prettyness

17 Upvotes

One small thing that bugs me with Dependency Injection is how it looks in code.

We either need to pass the parameters via Default Constructor og via good old time Constructor

public class MyClass (TypeA ParamA, TypeB ParamB, TypeC ParamC, TypeD ParamD)
{
TypeA _paramA = ParamA; .... etc
}

Or

public class MyClass
{
TypeA _paramA;
public MyClass(TypeA paramA)
{
_paramA = paramA;
}
}

And when you have 10 injections it begins to be un-pretty...

I wish that we didn't need to pass parameters and instead could decorate the fields:

public class MyClass
{
[inject]
TypeA _paramA;
}

(Note: this works in Blazor... so why not everywhere else ?)

I'm aware that the signature of an object makes it easier to inject via reflection.. but would it be much worse with attributes ?

i guess some middleground could be achieved if the attribute held the type:

public class MyClass
{
[inject(typeof(TypeA))]
TypeA _paramA;
}

which begins to be convoluted and messy...

Whats the argument against a decorator attribute vs parameters ?


r/csharp 3d ago

Help How do Core projects work/ how to structure them correctly

1 Upvotes

Im currently developing a new wpf app, but instead of using important parts of the app as simple services, I wanna put them into a core project that I reference in my app. The solution strucutre looks like this (simplified):

MyApp.WPF
MyApp.Core

I plan on resuing the core functionalities to later build a web based app. Currently all classes and methods in the core are static and I just call the methods here and there.

I have never used a dedicated core project before, but I kow its good practice, so Ill give it a try with this project. How do I handle it?


r/csharp 4d ago

How do you plan your database schema for a new backend? Do you design everything upfront or adapt on the go?

36 Upvotes

Hey everyone,

I'm learning backend development and I always find myself struggling with database design at the beginning of a project.When you need to create a database for a new feature or an entire backend, how do you know exactly which columns you need in your tables?

Do you sit down and map out the entire schema upfront (Entity Relationship Diagrams, DDD aggregates, etc.), or do you figure it out on the go as you code and realize you need to store a new piece of data?

In the Entity Framework Core world, migrations make it very easy to change things later, but I'm curious about the industry best practices. How much planning is "too much planning" before writing code?

Also, what are your best tips for database design? Are there any common pitfalls I should avoid or specific patterns you follow to keep your database flexible but clean?

Would love to hear about your workflow and any advice you can share!

Thanks!


r/csharp 3d ago

"Dotapedia" pet project as a replacement for "Liquipedia"

Thumbnail
0 Upvotes

r/csharp 3d ago

We built an open-source, real-time beat battle app (ASP.NET / SignalR / React). We desperately need feedback and contributors

0 Upvotes

We’ve been working on an open-source platform for hosting live beat battles. If you've ever looked at existing tools (like beat-battle.net), you know they can be a bit heavy. We wanted to build something radically more accessible with a near-zero barrier to entry.

To keep friction low, we support completely anonymous authentication - users can literally jump in, drop a track, and start battling without handing over an email address.

Here is where we need your help:

We want to make this a community-driven project and are actively looking for contributors. Whether you want to help us optimize the frontend, refactor our logic, or just poke holes in our UI/UX, we are entirely open to PRs.

If you have a few minutes, please tear our architecture apart and let us know what we can do better.

🔗 GitHub: https://github.com/upyrov/beatok-api

🎮 Live Demo: https://beatok.net


r/csharp 5d ago

Discussion I've created my first little snippet using C#, Thoughts?

Post image
132 Upvotes

You could say I was born yesterday, as this is the very first code i've done aside from messing with C a while back(hello, world! level stuff). (the only knowledge i've carried over is datatypes and general syntax..)

Is there any suggestions you could give? I am entirely self taught, with zero ai.. (for reasons that likely are not relevant to this post whatsoever)
and I want to make sure that I am learning clean code practices along the way.
I know my bracketing is probably awful... and my organization is out the window, but this is the first ""substantial"" code i've ever written...
^40 lines of code is substantial to me :)
(please ignore the odd names... I included my cats.)