Is it called "trio" state because 3 of the 5 states are not supported?
I also like how True is -1. Beautiful all around!
orthoxerox 5 hours ago [-]
-1 means every single bit is 1, the truest possible value.
nkrisc 2 hours ago [-]
I’m having a surprisingly difficult time deciding if I strongly agree or disagree with this statement.
orthoxerox 2 hours ago [-]
I know VB used -1 as the truth value, not sure about other languages.
saidnooneever 6 hours ago [-]
note CTrue, the one true true
biglyburrito 3 hours ago [-]
CTRUE IS A FALSE PROPHET AND ITS WORSHIPPERS SHALL BURN FOR THEIR HERESY
biglyburrito 4 hours ago [-]
More languages need to support enoms.
drdaeman 5 hours ago [-]
Usual reminder that one of the hardest problems in software engineering is still naming things ;-)
rich_sasha 11 hours ago [-]
Awful as it is, I can easily imagine how it happened... Probably says more about me than the code.
tgv 8 hours ago [-]
You're a true Romantic: Idealist and Pragmatist in one.
mycall 12 hours ago [-]
Could False = FileNotFound and this is a case of AST symbol constraints?
glimshe 18 hours ago [-]
I love C# and in every iteration we're getting more and more features to get C-like performance in a lot of scenarios. C# does it really well because if your problem isn't performance/memory-constrained, you can ignore these features and fallback on the language's natural ease of use.
kensai 15 hours ago [-]
Do you think by now C# has left Java behind in features and performance?
torginus 4 hours ago [-]
I never liked the C#/Java comparison - Java was designed as a much higher level language, and allows reasoning about low level abstractions a lot less, while doing a ton more optimization in the JIT.
For example, GC escape analysis, automatic lock elision, devirtualization, tiered compilation are fairly recent features in C#, and likely not as mature/powerful.
Or C# has generic specialization, so if your generic param is a stuct, you get a separate implementation, while Java generics work via type deletion.
But in C# you have a ton more synchronization primitives, value types, methods are non-virtual by default etc.
This usually means that expertly crafted C# code can be faster than Java (and more importantly, you can trust the compiler to do the right thing), while if you wrote it exactly like Java, you'd probably end up with slower code.
mrsmrtss 3 hours ago [-]
> while if you wrote it exactly like Java, you'd probably end up with slower code.
That's not the case for some time already, at worst you get similar performance with Java and with a little effort you can get significantly better performance.
goto11 8 hours ago [-]
C# was always better than Java as a language. The strength of Java is the ecosystem, and Java being open source and cross-platform from the beginning.
pregnenolone 4 hours ago [-]
Language design isn't just about adding every possible feature. For example, someone mentioned operator overloading. As someone who has written a lot of Scala, I think operator overloading would be a very bad feature for an enterprise language like Java which needs to be consistent above all else.
I never understood the obsession some people have with the C# vs Java debate anyway. Generally, both languages are very good at what they do, each having its own set of advantages and disadvantages. Regardless, a developer can pick up the other language with basically no effort.
xigoi 55 minutes ago [-]
> I think operator overloading would be a very bad feature for an enterprise language like Java which needs to be consistent above all else.
Operator overloading increases consistency. Instead of having
int a = b + c;
CustomNumberType x = y.add(z);
you have
int a = b + c;
CustomNumberType x = y + z;
fragmede 50 minutes ago [-]
The problem with operator overloading is it makes things confusing when mixing types and let's programmers write confusing code.
Person x;
Job y;
CustomType z = x + y;
WTF is Z?
Is the argument, anyway, I support operator overloading.
pjmlp 5 hours ago [-]
To the point that after all the drama with J++ that lead to .NET and C# development, Microsoft nowadays is also an OpenJDK contributor with their own distributions, and official developer advocacy channels on YouTube, conferences and devblogs.
Turns out they really want to have plenty of Java development on Azure as well.
littlecranky67 7 hours ago [-]
Java wasn’t open source at all from the beginning.
hackerqwe 6 hours ago [-]
And the binaries, the default sdk when using java, i.e. oracle jdk, is still not open source, encumbered with a mine field of legalese. For a long time it also included malware as ask toolbar. Stay away.
pjmlp 5 hours ago [-]
No, but it was free/gratis distributed on almost every developer magazine shipping with CDs.
One of the reasons why it took off.
lenkite 6 hours ago [-]
Java Virtual Threads are a superior paradigm to C#'s async/await and function coloring.
mrsmrtss 4 hours ago [-]
I don't get what the big problem is with function coloring. You basically only need async when doing IO, and you had better know when a function does it, or you may have a bad surprise at some point in the future.
oaiey 3 hours ago [-]
That! Okay, in 2026 this could be a LSP feature with some editor fanciness but this is a real benefit. My nitpick is that we do not have a depreciation on the non async ones
hackerqwe 6 hours ago [-]
Clearly legacy heavy weight threads, virtual or not, are not superior. That’s why Swift, Rust and Typescript all chose async/await for concurrency.
lenkite 6 hours ago [-]
We are not taking about legacy heavy weight OS/platform threads. But "green" threads managed by the language runtime like Go. Java went the Go/Erlang way.
> Clearly legacy heavy weight threads, virtual or not, are not superior.
Associating virtual threads with "legacy heavy weight threads" is a fundamental misunderstanding
> That’s why Swift, Rust and Typescript all chose async/await for concurrency.
And Java chose to join Team Go/Erlang. At the end of the day, async/await is just syntactic sugar for futures/promises, which are essentially a way out of callback hell.
Besides, Rust and Typescript aren't good examples here: a green-thread scheduler (a runtime component) contradicts Rust's philosophy, while Typescript is inherently constrained by Javascript.
pjmlp 5 hours ago [-]
Except one of the milestones for .NET 11 is to offer similar mechanisms for async/await.
> We have chosen to place the green threads experiment on hold and instead keep improving the existing (async/await) model for developing asynchronous code in .NET. This decision is primarily due to concerns about introducing a new programming model. We can likely provide more value to our users by improving the async model we already have. We will continue to monitor industry trends in this field.
> Runtime async is a major runtime feature in .NET 11 that introduces new runtime-level infrastructure for async methods. The goal is to improve tooling and performance for async-heavy codepaths. For more details and to track progress, see the Runtime Async epic issue.
youre-wrong3 5 hours ago [-]
Hahahha no. lol just no.
brikym 12 hours ago [-]
It always has.
pjmlp 9 hours ago [-]
Only if we ignore that nowadays JVM does a better job at being the CLR, while Microsoft has forgotten what the C means.
14 hours ago [-]
biglyburrito 4 hours ago [-]
Speaking as somebody that spent 2yrs as a full-time Java dev before returning to the Microsoft stack: yes.
Java’s Optional sucks compared to how C# (and Kotlin) implement support for nullable types. C#’s async/await syntax is better than… however the hell Java says to implement asynchronous calls now (Thread? CompletableFuture? idk, I never figured it out). ffs, Java doesn’t even have support for string templates yet — they added it as a JDK preview feature (JDK 21?) and then removed it before final release.
gfody 14 hours ago [-]
more than 10 years ago, yes
paavohtl 10 hours ago [-]
More like 25. C# 1.0 already had capabilities Java developers are still dreaming of, like structs / value types, properties and operator overloading. C# 2.0 in 2005 introduced generics, implemented far more competently than Java ever did.
joe_mwangi 8 hours ago [-]
Notice you point out features that were easy to add during the beginning where there was no concern of backward compatibility? Now that java is porting value classes to mainline and we might have them soon, and planned operator overloading through type class, I believe java approach is making careful design choices that are semantically sound, rather than adding features that create edge cases such as boxing invariants in unions like C#.
mrsmrtss 7 hours ago [-]
So you try to say that Java gets to be more semantically sound by making bad choices early on? That does not make sense. Those choices are very difficult fix today and many of them can't be fixed. Say what you want but semantically more sound Java won't be. And the boxing with C# unions can and will be addressed later, this was a deliberate choice by the team to bring unions earlier.
lostmsu 4 hours ago [-]
> and many of them can't be fixed... And the boxing with C# unions can and will be addressed later
No, they won't. C# already got itself into a corner with 32 bit arrays and 32 bit spans. And if unions are introduced as reference only that will never be fixed due to binary compatibility requirement.
pjmlp 9 hours ago [-]
The difference is BDFL or design by committee, a big difference between both ecosystems.
hirvi74 16 hours ago [-]
I daylight as a .NET dev professionally. I completely agree with what you have wrote, but I do not think C# is particularly unique in that regard. I would say many common compiled languages are on the same path, e.g., Swift, Java, Kotlin, etc.. As time progresses, I am finding it harder to justify using C# for a greenfield project.
za3faran 15 hours ago [-]
> As time progresses, I am finding it harder to justify using C# for a greenfield project.
Are you able to elaborate why? Just curious.
antonymoose 15 hours ago [-]
Not OP here - but for me it’s the open source ecosystem. Java just wins in terms of scope, scale, and stability.
I love C# the language, but the ecosystem is a ghetto.
Rohansi 14 hours ago [-]
I see this reason a lot but what are some actual examples of what is lacking in the .NET ecosystem vs. Java?
davewritescode 14 hours ago [-]
Large Apache ecosystem (Spark, Flink, Pinot) is completely missing and third-party SDKS (looking at you AWS) almost ALWAYS have worse SDKs. The java Kinesis consumer and producer libraries are amazing, the ones for C# are simple wrappers around the AWS APIs which means there's a few foot guns waiting for developers to run into, even if they should know better.
Rohansi 12 hours ago [-]
Good point. The majority of Apache projects are Java. Amazon is also mostly Java internally.
Amekedl 14 hours ago [-]
Dev tools. The debugger is something for example that Microsoft ostensibly keeps to their own products, and how they totally slaughtered omnisharp.
It killed my daily csharp vscode driver couple of years ago, only now catching back up somewhat, but still unusable for bigger solutions.
That move made me gravitate towards vscodium, and avoiding csharp where possible.
Microsoft's move only recently got more understandable to me, because Cursor and others basically stole vscode to establish their "empire".
jayd16 10 hours ago [-]
If you can use Jetbrains, Rider is on par with IntelliJ. From that perspective, both languages have a best in class debugger.
369548684892826 8 hours ago [-]
Rider is very good but this subthread is about the lack of open source dev tooling.
biglyburrito 3 hours ago [-]
Support for OpenAPI 3.1 in .NET sucks. Up until recently, a third-party library (Swashbuckle) has been the heavyweight, but lagged for years in supporting new features & fixing old bugs. Microsoft created a first party option (Microsoft.AspNetCore.OpenApi) that supports 3.1, but it’s nowhere near feature parity with Swashbuckle yet.
I also find serialization/deserialization to be weak in .NET. Third-party Newtonsoft was king for years, then Microsoft released System.Text.Json. Years later, it lacks feature parity, including an easy way to debug like Newtonsoft did.
pjmlp 9 hours ago [-]
Lots of implementations and industry standards, many mix Java with OpenJDK.
It is not, Java is like C, C++, JavaScript and co.
There are many implementations, the language and runtime are evolving by industry partners, you get bare metal implementations with real time GC like PTC and Aicas (doing AOT for decades), JIT caches, cloud based JIT compilers (OpenJ9 and Azul), pauseless GC, an LLVM like compiler development framework (Graal),....
There are industry standards like Microprofile and Jakarta EE, which several vendors base their frameworks and application servers on.
And a mobile phone platform, which while isn't proper Java compliant, has enough pieces into it that makes it easier to integrate Java code and libraries, than using Xamarin.
Microsoft actually bothered with ECMA during the early days, however it hasn't been updated since C# 7.3, .NET Framework 4.8.
free652 14 hours ago [-]
I mean I haven't done much in c# recently, but few examples that c# ecosystem is the subpar in quality
Kafka client library sucks, I mean it was a nightmare to make it stable and there were a few of them.
Pdfbox library
And many other libraries. If you use c# Microsoft libraries only - then you are golden. outside of that its really bad.
At this point I switched to Rust.
JohannesH 7 hours ago [-]
A good built-in/open xslt3 processor.
sedatk 17 hours ago [-]
I've waited for union types on C# so long that I don't even care about syntax anymore. Just give us something that works. So, I appreciate the effort, I know it's taken at least a decade to get it into this shape, and much thought has gone into it. Kudos to the team.
rohitsriram 18 hours ago [-]
F# has had this for decades, C# is basically just slowly becoming F# with a C-style syntax. Not complaining though, most teams aren't switching languages so getting these features where people actually work is better than nothing.
munchler 18 hours ago [-]
F# leads the way and C# slowly catches up, as always. Yet for some reason, C# still gets all the mindshare.
correct_horse 18 hours ago [-]
Haskell, OCaml, Erlang lead the way and Rust, Zig and Go get all the mindshare. I feel like its a common pattern for more experimental languages to pioneer features and other languages to copy the features and bring them to a C style syntax that the majority of devs are familiar with.
cultofmetatron 18 hours ago [-]
Rust and Zig brought new ideas for memory management that Haskell, OCaml, Erlang sidestep having garbage control. its honestly amazing to me that they managed to get the adoption they have while being so innovative. I say this as a fulltime elixir dev.
ShalokShalom 15 minutes ago [-]
You would be surprised to see, how OCaml and the BEAM specifically think about memory.
unclad5968 13 hours ago [-]
What new ideas did Zig bring to memory management?
lenkite 6 hours ago [-]
Pluggable allocators. Allocators are passed to functions as arguments, the caller decides exactly how memory is managed. Maybe not "new" in idea, but "new" in being consistently applied everywhere in language & libraries.
pjmlp 5 hours ago [-]
Already Turbo Pascal for MS-DOS had a custom allocator API for its runtime.
All modern C++ collection types have allocators as type parameters, and this was already a thing in the compiler frameworks like OWL during the 90's.
lenkite 5 hours ago [-]
Zig makes allocation an explicit runtime concern:
var list = std.ArrayList(i32).init(allocator);
where allocator is a runtime value implementing the allocator interface.
Zig forces the caller to decide since allocator is part of the function contract. And this is consistent everywhere in Zig. Effectively speaking, this is universal, explicit & mandated dependency injection for memory management as opposed to to classic C++ STL allocators.
Sorry sir, I have a nostalgic fondness for C++ - it was my first language, but it just doesn't compare for flexible allocation convenience compared to Zig.
pjmlp 4 hours ago [-]
Fact remains it wasn't the first, and it remains to be seen how market relevant Zig will ever turn out be, especially after AI driven coding became mainstream.
The irony to argue about manual memory management ergonomic, when code is written by agents.
pjmlp 9 hours ago [-]
Zig is Modula-2, Ada 83 with a curly brackets, what new ideas?
skybrian 17 hours ago [-]
Being first isn't necessarily good if you get it wrong, though. Laziness by default and Hindley-Milner type inference seem like mistakes that simply aren't going to get cleaned up. Other languages make their own mistakes too.
fwip 16 hours ago [-]
What's wrong with Hindley-Milner?
skybrian 16 hours ago [-]
Leaving out types in public API's makes type errors hard to understand. Types should be declared in the API and bidirectional type inference used in the implementation.
Eh. This causes some problems for rust. Right now you can have a function return impl Trait instead of a concrete type. Very handy - and essentially required by async functions.
But the language also requires that types have names in lots of places. For example, you can't store an 'impl Trait' in a struct. You can't make a type alias of an impl Trait. And so on. As a result, async rust can only interact with a butchered subset of the language. (You can work around this with Box<dyn Future<...>> but performance suffers.)
There's a proposal[1] to fix this. But the proposal has been under discussion for (checks watch) 7 years now. Until this lands, async remains a second class citizen in rust.
This entire problem stems from rust's early decision to requiring concrete types at interface boundaries.
> I feel like its a common pattern for more experimental languages to pioneer features and other languages to copy the features and bring them to a C style syntax that the majority of devs are familiar with.
You're ignoring the fact that it's harder to bring new features to older languages as they have more bloat to deal with as not every idea turns into a success. So younger more focused languages can iterate more quickly. Also, being willing to make breaking changes makes things easier. Microsoft tries hard not to do that with C#.
Over time, maintaining any software becomes harder, languages are no exception. The fact that c# is still around, and still being developed is a feat in itself
jiggawatts 17 hours ago [-]
I wish I could find the reference, but there was a great blog / article by a computer science academic basically saying that OO, procedural, and functional paradigms are extremes of a design space where the “middle” of its Pareto frontier was essentially unknown until recent advances.
Moreover, many functional languages are getting pseudo-procedural features via the like of “do” syntax and monads, but that this is in some sense a double abstraction over the underlying machine that is already inherently procedural.
Starting from a language that is already procedural and sprinkling some functional abstractions on top is simpler to implement and easier for humans to use and understand.
Rust especially showed that many of the supposed advantages of functional languages are not their exclusive domain, such as sum types and a powerful type system.
Note the top comment especially, which explains succinctly why functional has rather substantial downsides.
jen20 15 hours ago [-]
The idea that Erlang is experimental is pretty amusing- it’s one of the most stable platforms there is.
nozzlegear 16 hours ago [-]
I love F#. It's my go-to language and one that I work with every day. Personally I feel that IDE support (as in perf, QoL features, etc.) is the only area it lags behind C#, and outside of that it's a clear winner for everything that I want to do with it.
pjmlp 9 hours ago [-]
Microsoft management has decided CLR has a new meaning, C# Language Runtime.
VB, C++/CLI and F# are only there because existing customers.
They have always behaved as if it had been a mistake to promote F# from research project into VS 2010 as an official language.
Since then it has been something that the teams never knew how to sell to the .NET customer base, pivoting from being only libraries for C# and VB, write unit tests, Web development, data analysis, whatever might make it.
However it was Standard ML, Miranda, Hope, OCaml and Haskell that lead the way, we aren't still fully there.
teh_klev 32 minutes ago [-]
> Microsoft management has decided CLR has a new meaning, C# Language Runtime.
> VB, C++/CLI and F# are only there because existing customers.
Oh, I think we need a citation for these claims.
nullhole 17 hours ago [-]
What types of problems are better solved in F# than C#?
Is having a combination of F# and C# in a single codebase possible? Is it recommended?
Akronymus 17 hours ago [-]
Easy code is much easier in f#, a lot of the time. Hard code is usually easier in f# due to the type system helping a lot. F# is also a lot more concise.
And yes, you can combine them, but afair, only in terms project boundaries. (You can include a c# project in an f# one and vice versa). There are a few cases where it's quite useful. For example, rewriting a part of a big project in f# to leverage the imperative shell - functional core architecture. Like rewriting some part that does data processing in f#, so that you can test it easier/be more confident in correctness, while not doing a complete rewrite at once.
Sort of like rust parts in the linux kernel.
munchler 11 hours ago [-]
All types of problems. F# can do almost anything C# can do and with less ceremony. The quote I like is that once you get comfortable with F#, switching back to C# is like "having to fill out government forms in triplicate".
bertylicious 13 hours ago [-]
I don't think it's a matter of the type of problem and I always found it weird how F# is being framed as being only useful for "math-heavy" problems.
What matters is what libraries you are gonna use for your solution. If most of them are C#-only and don't have an F# equivalent then you'll lose the ergonomics and conveniences that make F# so easy to work with.
moron4hire 17 hours ago [-]
It's very possible, even encouraged when you have workloads that call for it. F# is a great functional language, so it's good for parsers, compilers, etc. The support for units of measure is also really cool, making it great for scientific computing.
bob1029 8 hours ago [-]
C# gets all the mindshare because it's easier to understand and use on average.
We can all agree that F# is more clever and concise. No one is dying on that hill. But in terms of hacking your way through the customer requirements and working with a team of other humans, it cannot hold ground in the same way.
There is certainly not some concerted effort or lack of care involved. Microsoft could 10x the marketing budget around F# and the adoption rate probably wouldn't budge.
ShalokShalom 11 minutes ago [-]
That is entirely anecdotal and based on subjective interpretation of someone, who has worked in C like languages or something similar:
This is just about how you are used to it, it says nothing about the quality of the language itself.
xigoi 46 minutes ago [-]
I hate the trend of measuring “easy to understand” based on how superficially similar the language is to C/Java.
ShalokShalom 17 minutes ago [-]
How about F# compatability?
caioricciuti 16 hours ago [-]
About time. TypeScript and Rust proved how much cleaner code gets when you can model "this OR that" at the type level. The real test will be whether library authors start using them in public APIs or if they stay a curiosity.
frutiger 16 hours ago [-]
Standard ML proved this 50 years ago.
ComputerGuru 11 hours ago [-]
Why would the default language-level union keyword implementation force boxing? Seems like a crazy decision if it could just also implement the HasValue/TryGet itself and avoid it?
Metasyntactic 7 hours ago [-]
Hi there! C# language designer here, and one of the people working on unions.
Boxing is not something inherently to be avoided. It actually can work better in many (most?) use cases, and avoids a lot of problems that non-boxing approaches often cause (like tearing and copy costs).
It's try that the non boxing pattern could be implemented by us. And it's very reasonable that that is something we may do post this release. However, it's a non-trivial area. There's no one correct 'non-boxed' implementation. For example, do you have separate fields for all your unmanaged data? or do you have a blob of bytes that is large enough to align all your unmanaged data from teh largest set of of unmanaged fields, and you unsafe index into that?
Similar question for managed data. Do you have strongly typed fields for that data? Or do you attempt to use objects, to compact to as little space as possible? The former avoids casting costs. The latter allows you to minimize space. You can also potentially use unsafe casts. But those might introduce memory holes in tearing situations. etc. etc.
Because of this, i think the best outcome is to define the pattern (which we've done) and then use generators to allow you to control precisely the impl strategy, giving you all the bells and knobs you want to best fit your domain.
ShalokShalom 10 minutes ago [-]
Can we expect that the C# development team works with the F# crowd, to make this copied feature work on both?
Rapzid 8 hours ago [-]
Shame it'll be like 3 years until System.Text.Json sees support for serialization or exporting schemas for them..
biglyburrito 3 hours ago [-]
Or being able to debug exceptions as easily as in Newtonsoft.Json.
3plefly 8 hours ago [-]
[dead]
bartwe 16 hours ago [-]
As a big user and fan of c# but this is a miss, as it always boxes value types.
Contrary to what a lot of people guess, boxing is actually a really good strategy most of the time. And, is indeed what many people are doing here anyways. The design supports a pattern that allows for non-boxing, and I expect that we will both supply an implementation for that with reasonable defaults, and that source generators will be a great way to augment this to get highly specialized impl strategies for non-boxing depending on the varying domain needs any specialized customer may have.
viktorcode 5 hours ago [-]
It is a downer, but I would like to test the performance first in the practical scenario. I've been working on a project where tagged unions would literally saved us from complexity. If that to happen again later I would go for boxed implementation and swallow up the penalty.
hahn-kev 14 hours ago [-]
It always boxes them TODAY. Lately the team has been releasing an MVP and improving stuff (like perf) later on. I wouldn't be surprised if they do the same thing here, as noted in the article you can already work around that yourself.
algorithmsRcool 14 hours ago [-]
But why not do it right the first time. This is an obvious performance pitfall for people that want to adopt this feature. It is bizarre to me after the last decade has been dedicated to performance improvments.
hahn-kev 14 hours ago [-]
They do this often actually. They will likely watch how people use it and tailor the design to fix that.
As for performance, in lots of use cases it's not going to be a big deal. If you are super sensitive to performance issues then you can just wait, meanwhile everyone else gets to use the new feature. You have to start somewhere and waiting to satisfy everything usually ends up with doing nothing
Izikiel43 16 hours ago [-]
There is the non boxing option, and this is the first iteration of the work, it's not one and done.
zamalek 16 hours ago [-]
When I cared about C# (which is no longer the case), I was lightly involved in the discussion for this and sibling features - mostly theorycrafting exactly your ask: the JIT team very succinctly expressed extreme disinterest in adding support of any kind.
The C# compiler could do it to a degree, but there would be too many caveats to make it actually useful. Unless the JIT team has a change of heart, you're probably never going to see this.
za3faran 15 hours ago [-]
What do you use these days language-wise?
zamalek 13 hours ago [-]
I'm part of The Rust Evangelism Strikeforce. In all seriousness, whatever suits the task well. Rust is for passion projects where I want to enjoy coding something; I find Go to be more of a direct competitor to C# - but it has the edge due to lacking exceptions (which is 15 years wasted of my life, never again). I'm always searching for something better, though.
hahn-kev 18 hours ago [-]
I'm glad to finally see this making it's way into C#. Not so much because I want to use unions purely in C#. But because I want to be able to define them when interfacing with other languages.
moomin 18 hours ago [-]
AFAICT, this means you won’t be able to define Either<string, string>, which is definitely a thing you sometimes want to do.
sheept 18 hours ago [-]
It seems like if you wrap both in a record then it should be possible:
public record Left<T>(T Value);
public record Right<T>(T Value);
public union Either<L, R>(Left<L>, Right<R>);
Metasyntactic 7 hours ago [-]
Hi there. One of the C# lang designers here.
You're correct. The unions we're working on right now are 'type unions'. So the type is inherent in the union distinction, and you would not be able to distinguish that case. That said, we're also looking at full blown discriminated unions (you can look at one of my proposals for that here: https://github.com/dotnet/csharplang/blob/main/meetings/work...), which would allow for that. Syntax entirely tbd, but you'd do something like:
enum struct Either<T1, T2> // or enum class
{
First(T1 value),
Second(T2 value)
}
We view these features as complimentary. Indeed, if you look at the extended enum proposal, you'll see it builds on top of unions and closed types (another proposal coming in the next version of the lang).
jzebedee 18 hours ago [-]
C# is strongly-typed, not stringly-typed. The point of the union is to list possible outcomes as defined through their respective types.
The idiomatic way to do this would be to parse, don't validate [1] each string into a relevant type with a record or record struct. If you just wanted to return two results of the same type, you'd wrap them in a named tuple or a record that represented the actual meaning.
Interestingly, dynamic languages which make use of symbols (Ruby, Elixir, Common Lisp) probably fall closer to Haskell than Python or TS. Elixir example:
Where :yes and :no are memory-efficient symbols, not strings.
jaen 8 hours ago [-]
String literals are structural types which are way more expressive than regular (Haskell) ADTs, which are nominal types.
In TS in particular, in combination with other features (mapped types), they are equivalent to row polymorphism + whatever Haskell/GHC features enable type families to specialize on constant literal arguments (or you can use atomic types, but that's not structural / open-world)... so pretty advanced.
This is valid TS/Python:
type ABC = "A" |"B" | "C"
type AB = "A" | "B"
const x: AB = "A";
const y: ABC = x;
The equivalent Haskell requires using several extensions.
troad 7 hours ago [-]
I know. I literally gave the example of a Python Literal in the post you're replying to. TS too. :)
My overall point is that Haskell's type system is sufficiently expressive (you may not have "A" | "B" | "C", but you do have A | B | C) that there's no obvious remaining use case for string literals, unless you're thinking of typing input by way of expected literals instead of actually parsing it, which is... a choice. :P
jaen 5 hours ago [-]
By Haskell's type system do you mean with all the GHC extensions?
Because TypeScript has structural sub-typing, while standard Haskell (eg. `A | B | C`) has neither subtyping nor structural typing, which both are very useful features for safe "integration/glue" type of programs.
(String) literals form a fundamental part of the TS "row polymorphism" (record types) and eg. tuple union type implementation.
You can type a non-empty array that starts with zero...
> By Haskell's type system do you mean with all the GHC extensions?
No? What extensions does `A | B | C` require?
> Haskell has neither subtyping nor structural typing
Is subtyping back in? Good news for Java and C++.
Re structural typing, I would ask what behaviour you're after, specifically. For example, this is a valid, typed Haskell function for any two values that can be added, including any user-defined ones:
adder a b = a + b
If by structural typing you mean silently coercing types that the compiler deems structurally equivalent, then no, but I don't think many people writing Haskell would consider that desirable. A `Person` may have an age (40) and a `Wine` may have an age (2005), but you're not going to get sensible results if you start adding those two together, and your compiler should probably stop you.
Structural typing is the sort of thing that is very valuable if you're bolting a type system onto a language with a cornucopia of untyped structs, like JS objects. It is comparatively much less valuable if you're working in a typed ecosystem to begin with, since you're not liable to have loose untyped structs floating around that require coercion.
> "integration/glue" type of programs
It does sound a lot like you're using string literals in lieu of parsing foreign input, which strikes me as a pretty bad idea. Particularly in a language like TS, which is not type safe at runtime, and which will happily ingest an unexpected value, silently coerce it in all sorts of fun and wacky ways, and cause behaviour far removed from what any static analysis of the TS source would suggest.
> You can type a non-empty array that starts with zero
Can you please name me any possible actual use for this? Especially given the type doesn't even exist at runtime and will never be enforced on input data, so this is a once-off check for comptime constants?
jaen 3 hours ago [-]
OCaml and Scala, both also famously strongly typed functional languages, also have structural typing (OCaml even has many different kinds at many different levels!). Mainstream, Go is based on structural (interface) typing.
The Person/Wine example is a pointless strawman. That's not what structural typing is generally used for.
The entire comment is basically making up strawmans...
I didn't give practical examples to save space, obviously, it was just to disambiguate what I meant.
TypeScript has several runtime-safe advanced validators based on its type system (most well-known being Zod), capable of enforcing types similar to what I provided.
To conclude, these type system features were added by multiple experienced language designers for a reason, to languages that already had functional ADTs, so going "huh but what are these even useful for?!" to me sounds a bit clueless (or argumentative), so I don't see a productive continuation to this discussion.
troad 3 hours ago [-]
Haha, I knew you'd bring up Go. I even considered pre-emptively dropping Rust and Zig as counterexamples. I think most people who favour static typing consider the duck-typed interfaces of Go to be a mistake. Personally, I consider all of Go to be a mistake.
> these type system features were added by multiple experienced language designers for a reason
Oooh, an appeal to authority, where that authority isn't even named. I'll have you know a famous queen told me you're wrong on this, also for "a reason".
> TypeScript has several runtime-safe advanced validators based on its type system (most well-known being Zod), capable of enforcing types similar to what I provided.
Right, so TS typing is so amazing it requires runtime parser libraries from NPM, and Haskell is less sophisticated because it's not stringly typed.
You realise the entire, complete, exhaustive runtime schema for your zero-first non-empty integer array example looks like this in Haskell, right?
sch (0:_) = True
sch _ = False
That's a complete function that somehow manages to work without pulling in NPM dependencies. The best JavaScript minds of our generation remain baffled.
> The Person/Wine example is a pointless strawman
> I didn't give practical examples to save space, obviously, it was just to disambiguate what I meant.
So when you use illustrative examples, it is to "disambiguate what you meant" (huh?), and when I do it, they're "pointless strawmen". A little hypocritical, no?
> a bit ignorant
Honestly, I don't think you know what you're talking about at all. You clearly hadn't even read my comment when you started replying with Python and TS examples... that were already in my comment.
It also really sounds like you're using string literals to type input without properly parsing it, which is just a terrible idea. Haskell's type system is designed precisely to protect you from this sort of mistake. [0] No, you're not always going to get what you expect. No, your JS program will never let you know that's the case. No, a sane type system does not require mainlining runtime parser libraries from the biohazardous oceans of NPM. A schema in Haskell is going to be significantly shorter and sounder than anything in Zod, and you don't need a library for it.
As I said above, TS' type system makes sense for a type system bolted onto a dynamic language post facto. TS needs to more tightly link (even mildly conflate) values and types, since it needs to do a lot of clever narrowing to figure out what mad ball of JS it is dealing with at any given time. Haskell does not operate under any such constraint.
> I don't see a productive continuation to this discussion.
Phew. Timesaver.
Of course the irony of all this is that I use TS daily, and Haskell quite rarely.
Yeah, you're just continuing to take whatever was written argumentatively/maliciously as predicted.
Does not seem like this:
> Please respond to the strongest plausible interpretation of what someone says, not a weaker one that's easier to criticize. Assume good faith.
> Personally, I consider all of Go to be a mistake.
You also consider Scala and OCaml to be mistakes? Because all of what I've mentioned also works in a very similar way in Scala.
> an appeal to authority
No, I didn't appeal to authority. It's the opposite - it's statistics. Multiple experienced language designers don't add features later for nothing. For a similar process, see eg. closures getting added to every mainstream language.
> complete, exhaustive runtime schema
Again, I wasn't talking about runtime schemas, but types. I only mentioned runtime as a counterpoint to the false statement that TypeScript doesn't enforce this. Only reducing this to runtime checking is a fallacy, again.
> A little hypocritical, no?
No, they aren't comparable since I wasn't using the examples as supports for an argument of whether X is better than Y. Strawmen involve argumentation.
> read my comment... examples... that were already in my comment
I read it in detail, the problem is you didn't really read my comment in detail, which illustrated both the subtyping and structural typing aspects (albeit trivially, yes), which yours didn't.
> You're also fairly clearly using string literals to type input without properly parsing it
Okay then, the arrogance of this is pretty astounding... You seem to know what I'm doing better than I am!
To be clear, I'm not doing any of that. And I've written Haskell way before I wrote any TypeScript.
troad 42 minutes ago [-]
I believe I was promised a respite from this.
Everything I said to you prior to my last message was fairly gentle. I'm not sure what response you were expecting to what you wrote at that point, which was to accuse me of disingenuous strawman arguments and ignorance. Perhaps you yourself would have benefited from a rule refresher?
> You seem to know what I'm doing better than I am
Apparently so! Trust me, it gives me no pleasure, and I'd rather I didn't.
> Again, I wasn't talking about runtime schemas, but types. I only mentioned runtime as a counterpoint to the false statement that TypeScript doesn't enforce this. Only reducing this to runtime checking is a fallacy, again.
My dear friend, this is almost completely incoherent.
I wish to strictly type myself as a function at this point, whereby your messages are my input, and void is my output. Zod, activate!
nvlled 11 minutes ago [-]
I would say, with a striped-shirt and not a glove in my hand, that the person you were fighting with gets the score, and wins by technicality. I suggest you take the bench first and review your comments and reflect with a wet towel on your head.
nesarkvechnep 10 hours ago [-]
Thank you for the lecture but I didn’t mean that. I meant `Either String String` is possible in Haskell and not in C# because… C# is strongly-typed.
troad 9 hours ago [-]
You're welcome! Knowing is half the battle.
That Haskell snippet is just syntax sugar for Left(string) | Right(string), which is trivial in any language with unions.
Not clear why it would be an improvement over just naming the alternatives something meaningful, but if you're wedded to Left and Right, go for it.
10 hours ago [-]
goto11 16 hours ago [-]
You cant have a `type Foo = String | Strimg` in Haskell either.
bertylicious 12 hours ago [-]
But you can have an `Either String String` which is what GP was talking about.
bertylicious 9 hours ago [-]
My mistake. I see my oversight now. `Either String String` is not equivalent to `String | String`, but to `Left String | Right String`. The same must be done for the C# version.
goto11 8 hours ago [-]
Yes, you must have individual constructors for the left and right cases in order to distinguish them. In C# you would use two distinct record types for this. Haskell’s syntax is more concise though, since you define the constructors inline in the declaration of the sum type.
twodave 12 hours ago [-]
You can use implicit operators or a library like Vogen to accomplish the same thing in a way that they can be coerced as strings. This isn’t a real issue.
goto11 16 hours ago [-]
Well it is a type union. The union of string and string is just string.
bertylicious 12 hours ago [-]
No, it's a union of a left value (that happens to be a string) and a right value (that happens to be a string). But the compiler-generated code can't tell them apart.
jafffsuds 11 hours ago [-]
What you are describing is something different called a disjoint union which will maintain the identities of the left and right values when there is overlap.
The C# unions appear to behave like unions, not disjoint unions.
bertylicious 8 hours ago [-]
My mistake. I see my oversight now. `Either String String` is not equivalent to `String | String`, but to `Left String | Right String`. The same must be done for the C# version.
You are correct that this requires support for disjoint unions (aka tagged unions), which Haskell always had and C# will soon have.
throw1234567891 18 hours ago [-]
but can you define T1 and T2 of string, then use Either<T1, T2>?
eterm 17 hours ago [-]
Could you be clearer about what you mean, since string is a sealed type in C#, so what exactly do you mean T1 and T2 of string?
rawling 17 hours ago [-]
A record wrapping a string, indicating what the string represents, so you can't mix it up with a different thing also represented by a string.
eterm 17 hours ago [-]
Yes, you can have two different record types which both wrap a string value.
As a (bad) trivial example, you could wrap reading a file in this kind of monstrosity:
var fileResult = Helpers.ReadFile(@"c:\temp\test.txt");
Console.WriteLine("Extracted:");
Console.WriteLine(Helpers.ExtractString(fileResult));
public record FileRead(string value);
public record FileError(string value);
public union FileResult(FileError, FileRead);
public static class Helpers
{
public static FileResult ReadFile(string fileName)
{
try
{
var fileResult = System.IO.File.ReadAllText(fileName);
return new FileRead(fileResult);
}
catch (Exception ex)
{
return new FileError(ex.Message);
}
}
public static string ExtractString(FileResult result)
{
return result switch
{
FileError err => $"An Error occured: {err.value}",
FileRead content => content.value,
_ => throw new NotImplementedException()
};
}
}
Now, such an example would be an odd way to do things ( particuarly because we're not actually avoiding the try/catch inside ), but you get the point. Both FileRead(string value) and FileError(string value) wrap strings in the same way, but are different record types, and the union FileResult ties them back together in a way where you can tell which you have.
It's more useful implemented a level deeper, so that the exception is never raised and caught, because exceptions aren't particularly cheap in .NET.
16 hours ago [-]
spicyusername 3 hours ago [-]
C# is such an underrated language.
A nice balance of language features and legibility.
jdw64 17 hours ago [-]
C# is my strongest and favorite language. That said, it's frustrating that the C# framework ecosystem lacks solid options. MAUI is especially half-baked, and I'm really starting to doubt whether I should continue using XAML
mynameisash 17 hours ago [-]
C# used to be my favorite language, but having spent a lot of time in Rust using its algebraic data types + match statements + Option & Result types, then returning to C# to build a few moderately involved libraries, I'm horrified by the enums and null & error handling that I used to deal with all the time.
I knew that enums were really just named integer values and nothing more, but I had forgotten than you can build a perfectly legal enum from an integer out of the bounds of the enum's range. And a switch statement is non-exhaustive. (As I said, it had been a while since I used C# extensively.) What would have been a few lines of code in Rust turned into dozens to try to exhaustively protect against invalid input.
I know C# is a mature language that has been around for decades, but how janky everything feels comparatively really shocked me. I only very briefly played with F# about a decade ago, but my guess is that I could try to pick that up and call F# from C#, getting much better ergonomics with a combination of the two.
electroly 16 hours ago [-]
> I had forgotten than you can build a perfectly legal enum from an integer out of the bounds of the enum's range. And a switch statement is non-exhaustive
These are solved by the new feature described in the article that we're commenting on right now. They're giving us unions and exhaustive switch. Ctrl+F "canonical way to work with unions" in the article to see an example. One of the best parts about C# is they never stop bringing useful features from other languages back home to us in C#. It makes for a large language with a lot of features, but if we really want something, we'll eventually get it in C#.
at_compile_time 14 hours ago [-]
Learning Rust really ruined C# for me. The explicitness saves you from so much defensive programming.
jdw64 17 hours ago [-]
[dead]
noveltyaccount 1 hours ago [-]
Same. I wish there was a good story for .NET UI on desktop, mobile, and web. I find Maui Blazor Hybrid to be pretty close. The desktop and mobile variants compile to a webview bound to native code (no WASM, no JS), and the Web variant compiled to WASM. Much leaner than Electron. Pretty clunky though last time I tried though that was three years ago.
bob1029 17 hours ago [-]
Winforms is better than ever. You can use it with .NET10 and WebView2 is a thing now.
makotech221 17 hours ago [-]
Winforms, wpf, blazor, maui, avalonia, what are you talking about
jdw64 17 hours ago [-]
Alright. I'm actually fine with WinForms and WPF since my factory floor codes depend on them. But the reality is they aren't expressive enough for modern UIs. XAML is an issue, and WPF is boilerplate hell. But then Blazor is too heavy, MAUI is broken and buggy, Avalonia is underwhelming, and WinUI 3 is an absolute nightmare.
Rohansi 14 hours ago [-]
> But the reality is they aren't expressive enough for modern UIs
Other than web tech, what actually is expressive enough?
tancop 5 hours ago [-]
[dead]
sedatk 17 hours ago [-]
> Avalonia is underwhelming
How? Can you elaborate?
vitally3643 16 hours ago [-]
Not OP, but I've found Avalonia to be pretty much a direct replacement for WinForms. I mean that both as a compliment and a deserved insult. It's not the WinForms we wanted, but it is the one we deserve.
More seriously, it has all the strengths and weaknesses of WinForms and feels about exactly as unfinished and rough as WinForms. I still have to implement custom widgets that i would have expected to be included out of the box. It's nice that it's cross-platform, though with all the rough edges that cross-platform .net still has. It really, truly feels exactly like every C# UI framework I've ever used in the last 20 years: almost good, not quite finished, and takes an amount of effort that is just unreasonable compared to any other language/framework of any age.
I've been a C# dev for most of my career. I have more fun writing UIs from scratch by drawing individual pixels in C++ than any C# UI.
sedatk 16 hours ago [-]
I'm truly surprised that it feels that underdeveloped. They market Avalonia as a direct replacement for WPF too. So, I'd expect it at least match WPF to be fair.
vitally3643 16 hours ago [-]
I would argue quite fervently that WinForms is more than a match for WPF. The only thing worse than WPF is UWP. We don't talk about UWP.
jdw64 17 hours ago [-]
[dead]
Salgat 17 hours ago [-]
What I don't get is why Java doesn't get dogged for desktop UI like C# does.
blanched 17 hours ago [-]
Because Microsoft pushes C#/dotnet as the preferred way to write UI on Windows.
ethin 13 hours ago [-]
Eto.forms too...
merb 3 hours ago [-]
sadly there is no ad hoc way of defining them. I do not care if they are boxed. I just want to say Success or Error1 or Error 2. Maybe I can live with or | or other stuff but not having ad hoc unions is basically not cool.
cubefox 16 hours ago [-]
Most people don't know that there are fundamentally two different kinds of "union" types: "tagged unions" and "untagged unions". Now .NET is introducing tagged unions, but unfortunately they stick to the popular tradition of calling them just "unions", which greatly adds to the confusion.
To clarify, these tagged unions are fundamentally different from the untagged unions that can be found in languages like Typescript or Scala 3.
Tagged unions (also called "discriminated unions" or "sum types") are algebraic data types. They act as wrappers, via special constructors, for two (or more) disjoint types and values. So a tagged union acts like a bag that has two (or more) labelled ("tagged") slots, where each slot has exactly one type and exactly one of these slot can take a value.
Untagged unions are set theoretic (rather than algebraic) data types. They don't require wrapping via a special constructor. They behave like the logical OR. They are not disjoint slots of a separate construct. A variable or function x with the type "Foo | Bar" can be of type Foo, or Bar, or both. To access a Foo method on x, one has to first perform a typecheck for Foo, otherwise the compiler will refuse the method call (since x might only have the type Bar which would produce an exception). If a variable is of type A, it is also of type A|B ("A or B"). There are also intersection types (A&B) which indicate that something has both types rather than at least one, and complement/negation types (~A indicates that something is of any type except A). Though the latter are not implemented in any major language so far.
jaen 7 hours ago [-]
These are not what are commonly called tagged unions. It's actually closer to an untagged union.
The C# union does not store any discriminator. Just look at the implementation - it's a single `object?` field.
The discriminative part is handled by run-time type information, which is stored in the object itself, not the union - which is why the C# built-in implementation requires boxing.
Also, you can use the same class/record type ("discriminator") in several different unions - again, a feature which ADTs/sum-types/tagged unions in most functional languages do not have.
You can even store one single object (ie. identical by reference equality) in several different union values at the same time, theoretically, which in combination with mutability is... uhh, certainly not common functional/mathematical semantics.
troad 15 hours ago [-]
Underlyingly, all unions are the same concept, exposed by C's `union` keyword, namely overlapping memory (as opposed to `struct`s, which are sequential memory). You can add a discriminator tag to your unions, your call. If it is impossible for there to be ambiguity (e.g. you track the state somewhere else, and you're dealing with a large array), it may be redundant / memory inefficient to tag every item.
Having these tags be a language construct is just a DX feature on top of unions. A very handy one, but it doesn't make tagged and untagged unions spring from different theoretical universes. I enjoy the ADT / set-theoretic debate as much as the next PL nerd, but theory ought to conform to reality, not vice versa.
cubefox 13 hours ago [-]
That's like saying Haskell is really an imperative language just because it's written in C. But it doesn't matter how it is implemented, it matters how it behaves on the surface.
troad 13 hours ago [-]
> That's like saying Haskell is really an imperative language just because it's written in C
I honestly don't even remotely understand how you got to that from what I wrote.
Unions already have a definition. You cannot go around claiming that technically unions are not unions (and that "most people don't know" this), because theory X or Y overloads the term union to refer to some unrelated concept. That's fine and well and good, within that theory, but it does not displace the usual CS definition of union. It is a load-bearing definition.
A tagged union is so called because it is a union (overlapping memory) with a field (a tag) containing a discriminator (aka discriminated union). An untagged union is a union without this tag. These terms didn't come out of nowhere. They are transparent descriptors of what's happening.
It doesn't matter whether Haskell is implemented in C or Ruby, and it doesn't matter whether it's functional, object-oriented, or a DSL for modding Elden Ring, none of this changes what a union is. I'm very supportive of type theories exploring the option space for type constructs, but someone's going to have to implement these somehow. Such as with (tagged) unions. You know, that CS concept we have, with a settled and well understood meaning.
To be fair to you, I think you're letting a very narrow definition of 'union' shadow a much more usual and common definition of the word. And that's totally fine if that's the definition pertinent to you and your work, but if that's the case, maybe don't go around pontificating about how most people do not understand unions?
cubefox 12 hours ago [-]
> You cannot go around claiming that 'technically' unions are not unions
I never said this. I said that there are two different kinds of unions with quite different definitions and behaviors.
> A tagged union is so called because it is a union (overlapping memory) with a field (a tag) containing a discriminator (aka discriminated union). An untagged union is a union without this tag.
That alone doesn't sufficiently describe the "unions" in set theoretic type systems like TypeScript. As I said, these unions are not disjoint and don't involve the special constructor that tagged unions/discriminated unions/sum types in algebraic type systems do. They also have logical implications like A implying A|B. Or A|A being equivalent to A, which isn't the case for discriminated/tagged unions. Maybe they are implemented similarly under the hood, but that doesn't negate the difference.
Edit: It's probably fair to say that "untagged unions" in languages like TypeScript, Ceylon or Scala 3 (set theoretic type systems) are different from "untagged unions" in C. It only adds to the confusion...
troad 12 hours ago [-]
> Maybe they are implemented similarly under the hood
It's hard to know what to say to this. Tagged unions are not tagged unions, even if they are literal tagged unions? What?
I reiterate what I said in my previous comment, you're not using the ordinary definition of the term union, and this is causing confusion. A union may or may not be a "union" as understood within various academic type theories, that really depends on how any given theory defines that word, which can be any way it wants. But a union is a CS concept with a clearly understood meaning, and when used without added context to suggest it is to be interpreted in some theoretical way, it is understood in that ordinary way.
OP's article is clearly using 'union' to mean tagged unions - he even shows off their implementation, with a tag. The author assumes that his audience will understand what he's talking about when he uses the word union, and it's not causing anyone trouble in this comments section. The fact that alternative definitions within various theoretical paradigms is very nice, bless their hearts, but not really relevant.
You may prefer other definitions to the usual CS definition, that's certainly your prerogative, but - again - that's hardly grounds for taking an article and comment section that's using the commonplace meaning, and appearing to lecture others for failing to adhere to your idiosyncratic standards for what a union must be.
cubefox 12 hours ago [-]
See my edit above. There is the C terminology, and the TypeScript et al terminology, and it's the same "untagged" terminology for two different things. In any case, both these kinds of "untagged" unions are different from tagged/discriminated unions. So just calling them "unions" is ambiguous at best and confusing at worst.
troad 12 hours ago [-]
But no one is actually confused. You yourself understand what the author meant, from your comments. Everyone here understands what he meant.
It's neither ambiguous nor confusing to use the word union in CS. The only person who's making it so is you, by introducing semi-unrelated concepts from set theory that happen to have the same name as the established CS concept.
Why stop there? Maybe the author meant the Union, as in the United States? Itself quite ambiguous - does he mean the United States of Mexico, or the United States of the Ionian Islands? Is C# getting Corfu? Corfu dot net? :P
Clearly he thought that it's the same kind of union as in TypeScript and that in C# just the syntax is weird. Which is not the case. Some others who are not commenting are probably also not aware of the two kinds of union types (or three, counting C separately).
> It's neither ambiguous nor confusing to use the word union in CS.
Well, we disagree.
troad 9 hours ago [-]
I see no evidence the user is confused, they said they wished the syntax were similar to TS. Though they're not the same thing, they do have comparable uses, so it makes sense to wish for similar syntax to reduce cognitive overhead.
> Well, we disagree.
Most people here know the set theory definition of unions. It's simply a niche use, compared to the usual CS definition, which is the one used in the original article and now all the comments.
You're swimming upstream with a definition that doesn't reflect what is under discussion, which you decreed as though from on high, complete with the assertion that most people don't understand unions like you do. They do.
cubefox 6 hours ago [-]
> they do have comparable uses, so it makes sense to wish for similar syntax to reduce cognitive overhead
No this makes no sense at all. Set theoretic types don't use special constructors, there is no way to make them look remotely similar. He is clearly not aware that these are different kinds of unions.
> They do.
Nope, precisely because they are less common. You yourself also clearly also didn't understand the difference between "untagged unions" in C and set theoretic type systems.
troad 4 hours ago [-]
Uh huh, sure. I didn't know the between a C union and a set theoretic union. I'm just so gosh darn confused, trying to use them set theoretical types in my C all the time!
You have come into a room full of CS practitioners to announce to them that you alone understand what unions are. Never mind fifty years of industry practices and nomenclature - never mind the fact we all already know set theory and unlike you don't confuse set theoretic unions with tagged unions - all that can now be set aside because you discovered set theory last week and now no one understands unions except for you.
Can't wait for next week when you discover some new band, and you'll be in here telling us how no one gets music except for you. :P
12 hours ago [-]
deadeye 18 hours ago [-]
I wish the syntax looked more like typescript. This will confuse my eyes for a while.
ameliaquining 17 hours ago [-]
It works quite differently from TypeScript, so the syntax used there wouldn't have worked.
18 hours ago [-]
SuperV1234 17 hours ago [-]
Boxed, and needs complex incantations to avoid the boxing. Meh.
Note that my expectation would be that the non-boxed form would be as trivial as adding `[NonBoxedUnion(SomeImplStrategyChoiceEnum)]` (or `[NonBoxedUnion]` for some default strategy choices that likely are ok).
This would give you extremely fine grained flexible choice on how you wanted your non-boxing union to work. There's no single right answer. There are just tradeoffs in terms of space/speed/copying-costs/memory-safety/etc.
I think it would make the most sense as people who care about boxing will have very different views and needs in terms of things like space, casting costs, copying speed etc.
The vast vast majority of users do not need to care at all. And for that, a boxed approach works exceptionally well.
msie 11 hours ago [-]
Wow! I remember unions back in my Uni days. So many years ago.
pdimitar 14 hours ago [-]
If C# can get them then Golang can get them as well!
Come on Gophers! It's time.
LAC-Tech 17 hours ago [-]
Wow 2016 would have loved this news.
Quarrelsome 18 hours ago [-]
I mean yes, but also: uh-oh.
I'm looking forward to reading some code that is even more confusing than the code I'm already reading.
Not entirely convinced that I see the usecase that makes up for the potential madness.
zoogeny 17 hours ago [-]
This is a classic debate in programming, literally:
2001: "Beating the Averages" (Paul Graham) [1]
2006: "Can Your Programming Language Do This?" (Joel Spolsky) [2]
Both of these articles argue for the thesis that programmers that have been deprived of certain language features often argue that they don't need those features since they are already comfortable working around the lack of said features.
It's a fancy way of arguing: you don't know what you're missing because you've never had it. Or, don't knock it until you try it.
Consider, is your argument a) I've never used it and don't see a need for it, or b) I've used it before and didn't get any benefit?
I can already do functional programming like map/reduce in C# tho. Not sure what the LISP argument is. Spolsky was saying there's a perf benefit in there somewhere but I'm not seeing how unions give me that.
zoogeny 17 hours ago [-]
You have at least two options:
1. Argue from ignorance. Never try unions in any other programming languages and completely disallow their use in C# codebases that you participate in.
2. Try them out and adopt an informed opinion.
You may even choose to remain in ignorance until someone wastes their own time trying to convince you. But it isn't my job or desire to teach someone who won't put in the effort to learn for themselves.
Quarrelsome 5 hours ago [-]
its not your job to comment spitty replies either but yet you volunteer that time, when you could have been productive instead of whatever the fuck this shit is.
My primary concern with this pattern versus exceptions is calling code can simply discard the resulting problem.
17 hours ago [-]
Sharlin 18 hours ago [-]
Discriminated union types are a really fundamental building block of a type system. It's a sad state of matters that many mainstream languages don't have them.
Quarrelsome 18 hours ago [-]
ok, so what problems do they help me solve that I can't already solve? Is it just that we can make code more concise or am I missing a trick somewhere?
bertylicious 12 hours ago [-]
I think it's almost always about making code more concise and programming more ergonomic. Assembly could already solve all the problems higher-level languages can solve. Yet we didn't discard them as useless.
JCTheDenthog 17 hours ago [-]
Simple example that I use often when writing API clients:
In current C# I usually do something like
public class ApiResponse<T>
{
public T? Response { get; set; }
public bool IsSuccessful { get; set; }
public ErrorResponse Error { get; set; }
}
This means I have to check that IsSuccessful is true (and/or that Response is not null). But more importantly, it means my imbecile coworkers who never read my documentation need to do so as well otherwise they're going to have a null reference exception in prod because they never actually test their garbage before pushing it to prod. And I get pulled into a 4 hour meeting to debug and solve the issue as a result.
With union types, I can return a union of the types T and ErrorResponse and save myself massive headaches.
Quarrelsome 17 hours ago [-]
I think I get it but I'm not really sure what I'm gaining over exception types. With an intelligent use of exceptions I can easily specify the happy path and all the error paths separately which seems really nice to me, because usually the behaviour between those two outcomes is rather different.
Akronymus 16 hours ago [-]
> I think I get it but I'm not really sure what I'm gaining over exception types. With an intelligent use of exceptions I can easily specify the happy path and all the error paths separately which seems really nice to me, ...
Until your coworker comes along and accidentally refactors the code to skip the exception catching and it suddenly blows up prod.
With tagged unions you can't accidentally dereference to the underlying value without checking if it's actually proper data first.
Quarrelsome 5 hours ago [-]
> Until your coworker comes along and accidentally refactors the code to skip the exception catching and it suddenly blows up prod.
can't my co-worker just use this pattern and discard an error result the same? I'd argue its easier as the stack wont unwind by default because the error is returned instead of thrown.
Akronymus 34 minutes ago [-]
Not quite, as the compiler wouldnt let let you use the "value" in that case. So if you discard the error path, you simply wont have any value to use further on in the code.
JCTheDenthog 17 hours ago [-]
Exceptions are significantly slower than normal control flow in C# (about 10,000 times slower). It's also pretty non-idiomatic in both C# and most other languages I've worked in to use exceptions instead of a switch statement or similar to handle an HTTP error code. Also there can be multiple possible non-error responses from an endpoint you need to differentiate between, and exceptions would make zero sense in that case.
Quarrelsome 5 hours ago [-]
> Also there can be multiple possible non-error responses from an endpoint you need to differentiate between
Yeah, I'm mildly sold on this use-case to be fair. But I think I'll keep the unexpected errors as exceptions.
rspeele 14 hours ago [-]
Object-oriented polymorphism (interfaces, inheritance) is for when you have a fixed set of methods to implement but an unbounded set of types that may want to implement them.
As a consumer, you cannot change the methods, but you can add a subtype. When you subtype an abstract class or an interface, the compiler does not let you proceed until you have implemented all the methods.
Discriminated unions are for the exact opposite situation, when you have a fixed set of subtypes, but unbounded set of methods to implement on them. As a consumer, you cannot add a subtype, but you can add a new method. When you write a new method, the compiler does not let you proceed until you have handled all the subtypes.
Good languages should support both!
The best example is abstract syntax trees, the data types that represent expressions and statements in a programming language. "Expression" breaks down into cases: integer literal, string literal, variable name, binary operations like add(expr1,expr2), unary operations like negate(expr), function call(functionName, exprs), etc.
Clearly all of these expression subtypes should belong to a base type `Expression`. But what methods do you put on `Expression`? If you're writing a compiler, you have to walk this syntax tree many times for very different purposes. First you might do a pass on it where you "de-sugar" syntax, then another pass where you type-check it and resolve names in the code, then another pass where you generate assembly code from it. Perhaps your compiler even supports different backends so you have a code-gen path for x86, another for ARM, etc. You'll likely want a pretty-printer so you can do automatic reformatting, maybe you want linting support, etc.
If you look at all those concerns and say that each subtype of `Expression` must implement methods for each one, then you end up with untenable code organization. Every expression subtype now has a huge stack of methods to implement all in one file, dealing with stuff from totally different layers of the compiler. It's a mess.
It's much cleaner to have the "shape" of the expression defined in one place without all that clutter, and then in each of those areas of the code you can write methods that consume expressions however they need, so each of those separate concerns lives in its own silo.
If you're an old hand at OO you may be familiar with its actual answer to this problem, the "Visitor" pattern. See System.Linq.Expressions.ExpressionVisitor. However, once you've used a language with good union and pattern matching support, this feels like a clunky hack. Basically the mirror image of a language without real object orientation imitating it by passing around closures and structs-of-closures.
------------------------------------------------
It doesn't just have to be compiler stuff. A business app data model can use this too. Instead of having:
public class DbUser
{
public EmailAddress Email { get; set; }
public PasswordHash? Password { get; set; } // null if they use SSO
public SamlEntityProviderId? SamlProvider { get; set; } // null if they use password auth
}
You could have:
type UserAuth =
| PasswordAuth of PasswordHash
| SSOAuth of SamlIdentityProviderId
The implementation details of those different auth methods, the UI for them, etc. don't have to be part of the data model. We do have to model what "shapes" of data are acceptable, but "doing stuff" based on those shapes is another layer's problem.
Quarrelsome 5 hours ago [-]
thank you so much, that's extremely helpful <3.
bigstrat2003 18 hours ago [-]
I think "what problems do they solve that I can't already solve" is the wrong way to look at it. After all, ultimately most language features are just syntactic sugar - you could implement for loops with goto, but it would be a lot less pleasant. I think that unions aren't strictly necessary, but they are a very pleasant to use way of differentiating between different, but related, types of value.
Quarrelsome 17 hours ago [-]
Ok. I'm just trying to understand what code I'm replacing with them. Like I wanna see the before and after in order to gain the same level of excitment as other people seem to have for them.
Often the explanations just seem rather abstract which makes it harder to appreciate the win, versus the hideous sort of code that might appear when they're misused.
airstrike 17 hours ago [-]
They are so fundamental to the way I write code I can't imagine ever using a language that does not support them.
"Make invalid states unrepresentable."
arwhatever 14 hours ago [-]
I might suggest that anyone who wants to make it concrete to go through the article
while visiting https://dotnetfiddle.net and typing the code samples in, experimenting with what manner of changes and additions to the code cause the compilation to fail, and considering how you would leverage those abilities in your everyday development work.
I think this would be even more powerful if you then come back and re-read some of the pro-Union comments in this very thread.
speed_spread 17 hours ago [-]
The value is realized when you have both discriminated union types _and_ language pattern matching (not regex). Then it's not just a way to structure data but a way to think about how to process it.
ikekkdcjkfke 9 hours ago [-]
make the compiler check more stuff, helpful when expanding or refactoring
cubefox 16 hours ago [-]
> Discriminated union types are a really fundamental building block of a type system. It's a sad state of matters that many mainstream languages don't have them.
"Non-discriminated" unions (i.e. untagged unions) are even less supported. TypeScript seems to be the only really popular language that has them.
munchler 18 hours ago [-]
Unions are simpler than subclasses and more powerful than enums, so the use cases are plentiful. This should reduce the proliferation of verbose class hierarchies in C#. Algebraic data types (i.e. records and unions) can usually express domain models much more succinctly than traditional OO.
Quarrelsome 18 hours ago [-]
> so the use cases are plentiful
such as?
> This should reduce the proliferation of verbose class hierarchies in C#
So just as an alternative for class hierarchies? I mean good people already balance that by having a preference for composition.
munchler 18 hours ago [-]
Simple example:
type Expr =
| Primitive of int
| Addition of (Expr * Expr)
| Subtraction of (Expr * Expr)
| Negation of Expr
Quarrelsome 18 hours ago [-]
Isn't that just Func<int> ?
afdbcreid 17 hours ago [-]
Really not. You can, of course, having instead a delegate to evaluate the expression. But then that's all you can do. You can't pretty-print it, for example, or optimize it, or whatever.
17 hours ago [-]
LeFantome 17 hours ago [-]
“Compoision”. A typo I know but it would be a word describing what goes wrong with class hierarchies.
oompydoompy74 18 hours ago [-]
You don’t see the use case for… unions? I’ve got to stop reading the comments. It’s bad for my health.
adjejmxbdjdn 18 hours ago [-]
I love discriminated unions.
The problem with C# is that it’s so overloaded with features.
If you come from one codebase to another codebase by a different team it’s close to learning a completely new language, but worse, there is no documentation I can find that will teach me only about that language.
Throw in all the versioning issues and the fact that .Net shops aren’t great about updating to the latest versions, especially because versions, although technologically separated from Visual Studio, are still culturally tied to it, and trying to break that coupling causes all kinds of weird challenges to solve.
Then stuff like extensions means your private codebase or a 3rd party lib may have added native looking functionality that’s not part of the language but looks like it is.
Finally, keywords and operators are terribly overloaded in C# at this point, where a keyword can have completely different meanings based on what it’s surrounded by.
LLMs are a huge help here, since you can point to a line of code and ask them to figure it out, but it still makes the process of navigating a C# codebase extremely challenging.
So I can see why someone may be unhappy to see yet another feature. It’s not just this one feature. It’s the 100s of other features that are hard to even identify.
paddim8 17 hours ago [-]
I am all for minimalism but "If you come from one codebase to another codebase by a different team it’s close to learning a completely new language" I really don't agree. It's not that big. Just sounds like a skill issue
adjejmxbdjdn 12 hours ago [-]
Sure. Maybe it was a skill
Issue.
I switched between dozens of similar codebases over a period of 3-4 years (pre AI) when I was consulting and did multiple projects in multiple languages (well, only 1 in rust).
In my experience switching between the C# projects was always the worst. The codebase semantics diverged in ways I simply didn’t see in the Java/C++ codebases.
metaltyphoon 3 hours ago [-]
> C++ codebases
Now this one sounds almost unbelievable :). I’ve yet to see 3 or more C++ codebases using the same language feature set.
Quarrelsome 17 hours ago [-]
none of that applies to my position. I have an appreciation for almost all of C# and am comfortable in the framework. I just want to know what situations would be better suited to using them than traditional approaches.
I get there's an .Either pattern when chaining function calls so you don't have to do weird typing to return errors, but I'm using exceptions for that anyway, so the return type isn't an issue.
itishappy 16 hours ago [-]
The Result pattern can be a lot more ergonomic than exceptions.
Microsoft C# guidelines recommend try-parse (which is just the Result pattern, albeit somewhat cludgy with no unions) over exceptions.
the result pattern doesn't force you to handle the exception though. You can just discard the result.
itishappy 9 hours ago [-]
A function that returns `Result<T,E>` is not a `T` and cannot be implicitly converted to one. If you want to use that `T`, the only way is writing code that drops or handles the `E`. If you don't, your program does not compile.
Compare this to exceptions, where the type is just `T` and can be used without further ceremony. You can discard the error by forgetting a handler. Now you have a program that occasionally crashes.
Follow-up: Are there async exceptions? A `Result` is just data that can be awaited. How would that work with exceptions?
Quarrelsome 18 hours ago [-]
thanks for helping.
vips7L 18 hours ago [-]
Union/sum types are generally a good thing. Even Java added them. They tend to be worth “the madness”. Now the rest of all the crazy C# features might be a different question.
dgellow 18 hours ago [-]
What features do you see as crazy?
munchler 18 hours ago [-]
All the weird cruft around nullability, for starters. Once again confirming that allowing null references is usually a mistake.
dgellow 17 hours ago [-]
Do you mean the implicit nullable types? Now that you can make nullable explicit instead I really don’t have much issues with it. It is part of the type system, as it should, and you have null coalescing operators. Is it still problematic or are you dealing with older codebases where you cannot set the nullable pragma?
munchler 15 hours ago [-]
Yes, all that stuff. I try to stick to F# where no special syntax is required for missing values (via Option<T>).
vips7L 17 hours ago [-]
Maybe not crazy but the language just has a really broad surface. I find it to be like the Scala of the OO world.
bertylicious 12 hours ago [-]
Have you considered trying them out (maybe in F#) to understand why they are so popular in many other languages?
weinzierl 18 hours ago [-]
A common use case for the sum type is to define a Result (or Either) type. Now, C# not having checked exceptions is not as much in need for one as Java is, but I could still
imagine it being useful for stream
like constructs.
Quarrelsome 18 hours ago [-]
yeah this is the one I've considered as being mildly compelling. But don't we lose the fun of having exception handling as separate to the happy path?
exkgkkwksk 12 hours ago [-]
oo and support for exceptions, in particular checked exceptions, was a mistake of the 90s. We know better today, there’s a reason for why modern languages like go/rust/swift don’t use them, and why many use c++ with exceptions disabled.
andix 17 hours ago [-]
I've never been confused by language features. Usually the architecture or extreme indirection of the code is the confusing part.
patrickndaye919 5 hours ago [-]
[flagged]
antonvs 17 hours ago [-]
Did Anders Hejlsberg die, or something?
jafffsuds 11 hours ago [-]
He's been busy with the typescript-go project
le-mark 18 hours ago [-]
I used to see some excitement around .net core several years ago. I haven’t heard or seen much in the wild. Is anyone using .net on systems other than windows nowadays?
lol768 18 hours ago [-]
Yes; many (Alpine/Debian) containers in K8s on GKE for production rail ticketing infra in the UK.
There's not tons of noise being made because for the most part it all, Just Works and that's fairly boring. Perf, memory usage etc gets better every release. As an ecosystem, I'm pretty happy with it. I reach for other languages for smaller microservices.
gib444 18 hours ago [-]
> rail ticketing infra in the UK
You mean Raileasy? Or RDG too? (Just curious about the stack of the wider rail tech infra)
za3faran 15 hours ago [-]
What's preventing you from using C# for smaller microservices? And what do you reach for?
mrsmrtss 7 hours ago [-]
Maybe startup time was a problem before AOT?
dgellow 18 hours ago [-]
It’s huge in the game dev world, with Unity and Godot. .net also had a reasonable community on mobile for a while thanks to Xamarin, but I cannot imagine that many people using it for new mobile projects in 2026 (outside of game dev I mean).
It’s a very decent language (I mean C#) and runtime, I wish it had more market share in the startup world.
smlavine 18 hours ago [-]
An enterprise shop I co-op'd at was porting one of their apps from Xamarin to MAUI when I worked there, but certainly it doesn't have much mindshare (if any) amongst SE undergrads at my university.
unethical_ban 18 hours ago [-]
Someone I know who works with .net says that there is still no replacement for full Visual Studio for development, which is Windows only.
dgellow 17 hours ago [-]
Rider is the replacement, unless they are doing really specific (like WinUI2/UWP)
Rohansi 16 hours ago [-]
VS Code is also manageable. Or the CLI tools, if that's your thing.
Rider is definitely the most equivalent to full Visual Studio though.
aksss 11 hours ago [-]
I don’t think VS Code is remotely a replacement for VS/Rider. I use VS Code for a lot of things but for large and complex project sets the automation and features in VS are luxuries you really miss. It’s like going back to the Stone Age to use VS Code in those contexts. Trying to fill the voids in VS Code with extensions makes VS Code very brittle. VS Code has its lane but I think they are different tools suited to very different jobs.
rjbwork 14 hours ago [-]
I used to think this. Hopped to rider 4 years ago and haven't missed it except for .sqlproj development.
Rohansi 17 hours ago [-]
Unity is still using Mono these days which is missing basically all of the C# and .NET improvements from the past... 10 years now?
Godot was using Mono too but has since switched to .NET in version 4.
Still a great language and I hope Unity can hit their target to switch to .NET soon!
dgellow 16 hours ago [-]
Damn, I assumed they had switched to .net core, I cannot believe they are still stuck on mono. Thanks for the correction
bel8 18 hours ago [-]
I consulted for multiple enterprise C# projects in the last 5 years. At least two of them are 1mil+ lines of code each.
All of them run in Linux servers.
Some of them were ported from PHP and Python to C#.
Plus LLMs thrive in strongly typed languages.
Which means C# will keep being very strong in enterprise too. Not only in games where it reigns a large chunk of the market share.
18 hours ago [-]
mrsmrtss 7 hours ago [-]
For almost 10 years now, we have not published anything .NET to the Windows platform. .NET is more performant on Linux today than Windows, and I would say development is also better there (using Rider). However, we do still have devs who prefer Windows. We have built many critical systems on .NET and they just work, so they may be boring to some of the folks who like to have more excitement from their systems.
forgotaccount3 18 hours ago [-]
Yes, lambda's and our dev's use mac's so it enables that. We deploy some apps to some unix based server as well but the company is mostly windows servers anyway.
yread 18 hours ago [-]
Wwwuuuuuaaahhhhh! (making a big wild excited noise using asp.net core exclusively on Linux servers since 2017)
b65e8bee43c2ed0 18 hours ago [-]
it was an obvious marketing campaign. back then core and blazor were shilled relentlessly, and the artificial excitement died the moment MS moved on to shill vscode and typescript.
companies spend a lot on marketing, and it's not just ads.
I also like how True is -1. Beautiful all around!
For example, GC escape analysis, automatic lock elision, devirtualization, tiered compilation are fairly recent features in C#, and likely not as mature/powerful.
Or C# has generic specialization, so if your generic param is a stuct, you get a separate implementation, while Java generics work via type deletion.
But in C# you have a ton more synchronization primitives, value types, methods are non-virtual by default etc.
This usually means that expertly crafted C# code can be faster than Java (and more importantly, you can trust the compiler to do the right thing), while if you wrote it exactly like Java, you'd probably end up with slower code.
That's not the case for some time already, at worst you get similar performance with Java and with a little effort you can get significantly better performance.
Operator overloading increases consistency. Instead of having
you haveIs the argument, anyway, I support operator overloading.
Turns out they really want to have plenty of Java development on Azure as well.
One of the reasons why it took off.
https://javapro.io/2026/03/05/java-25-and-the-new-age-of-per...
https://docs.oracle.com/en/java/javase/26/core/virtual-threa...
Associating virtual threads with "legacy heavy weight threads" is a fundamental misunderstanding
> That’s why Swift, Rust and Typescript all chose async/await for concurrency.
And Java chose to join Team Go/Erlang. At the end of the day, async/await is just syntactic sugar for futures/promises, which are essentially a way out of callback hell.
Besides, Rust and Typescript aren't good examples here: a green-thread scheduler (a runtime component) contradicts Rust's philosophy, while Typescript is inherently constrained by Javascript.
https://github.com/dotnet/runtimelab/issues/2398
Which ended with,
> We have chosen to place the green threads experiment on hold and instead keep improving the existing (async/await) model for developing asynchronous code in .NET. This decision is primarily due to concerns about introducing a new programming model. We can likely provide more value to our users by improving the async model we already have. We will continue to monitor industry trends in this field.
Now three years later we have,
https://github.com/dotnet/core/blob/main/release-notes/11.0/...
> Runtime async is a major runtime feature in .NET 11 that introduces new runtime-level infrastructure for async methods. The goal is to improve tooling and performance for async-heavy codepaths. For more details and to track progress, see the Runtime Async epic issue.
Java’s Optional sucks compared to how C# (and Kotlin) implement support for nullable types. C#’s async/await syntax is better than… however the hell Java says to implement asynchronous calls now (Thread? CompletableFuture? idk, I never figured it out). ffs, Java doesn’t even have support for string templates yet — they added it as a JDK preview feature (JDK 21?) and then removed it before final release.
No, they won't. C# already got itself into a corner with 32 bit arrays and 32 bit spans. And if unions are introduced as reference only that will never be fixed due to binary compatibility requirement.
Are you able to elaborate why? Just curious.
I love C# the language, but the ecosystem is a ghetto.
It killed my daily csharp vscode driver couple of years ago, only now catching back up somewhat, but still unusable for bigger solutions.
That move made me gravitate towards vscodium, and avoiding csharp where possible.
Microsoft's move only recently got more understandable to me, because Cursor and others basically stole vscode to establish their "empire".
I also find serialization/deserialization to be weak in .NET. Third-party Newtonsoft was king for years, then Microsoft released System.Text.Json. Years later, it lacks feature parity, including an easy way to debug like Newtonsoft did.
It is not, Java is like C, C++, JavaScript and co.
There are many implementations, the language and runtime are evolving by industry partners, you get bare metal implementations with real time GC like PTC and Aicas (doing AOT for decades), JIT caches, cloud based JIT compilers (OpenJ9 and Azul), pauseless GC, an LLVM like compiler development framework (Graal),....
There are industry standards like Microprofile and Jakarta EE, which several vendors base their frameworks and application servers on.
And a mobile phone platform, which while isn't proper Java compliant, has enough pieces into it that makes it easier to integrate Java code and libraries, than using Xamarin.
Microsoft actually bothered with ECMA during the early days, however it hasn't been updated since C# 7.3, .NET Framework 4.8.
Kafka client library sucks, I mean it was a nightmare to make it stable and there were a few of them.
Pdfbox library
And many other libraries. If you use c# Microsoft libraries only - then you are golden. outside of that its really bad.
At this point I switched to Rust.
All modern C++ collection types have allocators as type parameters, and this was already a thing in the compiler frameworks like OWL during the 90's.
Sorry sir, I have a nostalgic fondness for C++ - it was my first language, but it just doesn't compare for flexible allocation convenience compared to Zig.
The irony to argue about manual memory management ergonomic, when code is written by agents.
https://jimmyhmiller.com/easiest-way-to-build-type-checker
But the language also requires that types have names in lots of places. For example, you can't store an 'impl Trait' in a struct. You can't make a type alias of an impl Trait. And so on. As a result, async rust can only interact with a butchered subset of the language. (You can work around this with Box<dyn Future<...>> but performance suffers.)
There's a proposal[1] to fix this. But the proposal has been under discussion for (checks watch) 7 years now. Until this lands, async remains a second class citizen in rust.
This entire problem stems from rust's early decision to requiring concrete types at interface boundaries.
https://github.com/rust-lang/rust/issues/63063
You're ignoring the fact that it's harder to bring new features to older languages as they have more bloat to deal with as not every idea turns into a success. So younger more focused languages can iterate more quickly. Also, being willing to make breaking changes makes things easier. Microsoft tries hard not to do that with C#.
Over time, maintaining any software becomes harder, languages are no exception. The fact that c# is still around, and still being developed is a feat in itself
Moreover, many functional languages are getting pseudo-procedural features via the like of “do” syntax and monads, but that this is in some sense a double abstraction over the underlying machine that is already inherently procedural.
Starting from a language that is already procedural and sprinkling some functional abstractions on top is simpler to implement and easier for humans to use and understand.
Rust especially showed that many of the supposed advantages of functional languages are not their exclusive domain, such as sum types and a powerful type system.
Update: Hah! ChatGPT found it: https://news.ycombinator.com/item?id=21280429
Note the top comment especially, which explains succinctly why functional has rather substantial downsides.
VB, C++/CLI and F# are only there because existing customers.
They have always behaved as if it had been a mistake to promote F# from research project into VS 2010 as an official language.
Since then it has been something that the teams never knew how to sell to the .NET customer base, pivoting from being only libraries for C# and VB, write unit tests, Web development, data analysis, whatever might make it.
However it was Standard ML, Miranda, Hope, OCaml and Haskell that lead the way, we aren't still fully there.
Oh, I think we need a citation for these claims.
Is having a combination of F# and C# in a single codebase possible? Is it recommended?
And yes, you can combine them, but afair, only in terms project boundaries. (You can include a c# project in an f# one and vice versa). There are a few cases where it's quite useful. For example, rewriting a part of a big project in f# to leverage the imperative shell - functional core architecture. Like rewriting some part that does data processing in f#, so that you can test it easier/be more confident in correctness, while not doing a complete rewrite at once.
Sort of like rust parts in the linux kernel.
What matters is what libraries you are gonna use for your solution. If most of them are C#-only and don't have an F# equivalent then you'll lose the ergonomics and conveniences that make F# so easy to work with.
We can all agree that F# is more clever and concise. No one is dying on that hill. But in terms of hacking your way through the customer requirements and working with a team of other humans, it cannot hold ground in the same way.
There is certainly not some concerted effort or lack of care involved. Microsoft could 10x the marketing budget around F# and the adoption rate probably wouldn't budge.
This is just about how you are used to it, it says nothing about the quality of the language itself.
Boxing is not something inherently to be avoided. It actually can work better in many (most?) use cases, and avoids a lot of problems that non-boxing approaches often cause (like tearing and copy costs).
It's try that the non boxing pattern could be implemented by us. And it's very reasonable that that is something we may do post this release. However, it's a non-trivial area. There's no one correct 'non-boxed' implementation. For example, do you have separate fields for all your unmanaged data? or do you have a blob of bytes that is large enough to align all your unmanaged data from teh largest set of of unmanaged fields, and you unsafe index into that?
Similar question for managed data. Do you have strongly typed fields for that data? Or do you attempt to use objects, to compact to as little space as possible? The former avoids casting costs. The latter allows you to minimize space. You can also potentially use unsafe casts. But those might introduce memory holes in tearing situations. etc. etc.
Because of this, i think the best outcome is to define the pattern (which we've done) and then use generators to allow you to control precisely the impl strategy, giving you all the bells and knobs you want to best fit your domain.
Contrary to what a lot of people guess, boxing is actually a really good strategy most of the time. And, is indeed what many people are doing here anyways. The design supports a pattern that allows for non-boxing, and I expect that we will both supply an implementation for that with reasonable defaults, and that source generators will be a great way to augment this to get highly specialized impl strategies for non-boxing depending on the varying domain needs any specialized customer may have.
As for performance, in lots of use cases it's not going to be a big deal. If you are super sensitive to performance issues then you can just wait, meanwhile everyone else gets to use the new feature. You have to start somewhere and waiting to satisfy everything usually ends up with doing nothing
The C# compiler could do it to a degree, but there would be too many caveats to make it actually useful. Unless the JIT team has a change of heart, you're probably never going to see this.
You're correct. The unions we're working on right now are 'type unions'. So the type is inherent in the union distinction, and you would not be able to distinguish that case. That said, we're also looking at full blown discriminated unions (you can look at one of my proposals for that here: https://github.com/dotnet/csharplang/blob/main/meetings/work...), which would allow for that. Syntax entirely tbd, but you'd do something like:
We view these features as complimentary. Indeed, if you look at the extended enum proposal, you'll see it builds on top of unions and closed types (another proposal coming in the next version of the lang).The idiomatic way to do this would be to parse, don't validate [1] each string into a relevant type with a record or record struct. If you just wanted to return two results of the same type, you'd wrap them in a named tuple or a record that represented the actual meaning.
[1] https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...
It would seem pretty unnecessary in Haskell, where you can just define whatever types you want without involving strings at all:
Of course you'd need a trivial parser, though this is probably a good idea for any string type: Interestingly, dynamic languages which make use of symbols (Ruby, Elixir, Common Lisp) probably fall closer to Haskell than Python or TS. Elixir example: Where :yes and :no are memory-efficient symbols, not strings.In TS in particular, in combination with other features (mapped types), they are equivalent to row polymorphism + whatever Haskell/GHC features enable type families to specialize on constant literal arguments (or you can use atomic types, but that's not structural / open-world)... so pretty advanced.
This is valid TS/Python:
The equivalent Haskell requires using several extensions.My overall point is that Haskell's type system is sufficiently expressive (you may not have "A" | "B" | "C", but you do have A | B | C) that there's no obvious remaining use case for string literals, unless you're thinking of typing input by way of expected literals instead of actually parsing it, which is... a choice. :P
Because TypeScript has structural sub-typing, while standard Haskell (eg. `A | B | C`) has neither subtyping nor structural typing, which both are very useful features for safe "integration/glue" type of programs.
(String) literals form a fundamental part of the TS "row polymorphism" (record types) and eg. tuple union type implementation.
You can type a non-empty array that starts with zero...
Now try in Haskell.No? What extensions does `A | B | C` require?
> Haskell has neither subtyping nor structural typing
Is subtyping back in? Good news for Java and C++.
Re structural typing, I would ask what behaviour you're after, specifically. For example, this is a valid, typed Haskell function for any two values that can be added, including any user-defined ones:
If by structural typing you mean silently coercing types that the compiler deems structurally equivalent, then no, but I don't think many people writing Haskell would consider that desirable. A `Person` may have an age (40) and a `Wine` may have an age (2005), but you're not going to get sensible results if you start adding those two together, and your compiler should probably stop you.Structural typing is the sort of thing that is very valuable if you're bolting a type system onto a language with a cornucopia of untyped structs, like JS objects. It is comparatively much less valuable if you're working in a typed ecosystem to begin with, since you're not liable to have loose untyped structs floating around that require coercion.
> "integration/glue" type of programs
It does sound a lot like you're using string literals in lieu of parsing foreign input, which strikes me as a pretty bad idea. Particularly in a language like TS, which is not type safe at runtime, and which will happily ingest an unexpected value, silently coerce it in all sorts of fun and wacky ways, and cause behaviour far removed from what any static analysis of the TS source would suggest.
> You can type a non-empty array that starts with zero
Can you please name me any possible actual use for this? Especially given the type doesn't even exist at runtime and will never be enforced on input data, so this is a once-off check for comptime constants?
The Person/Wine example is a pointless strawman. That's not what structural typing is generally used for.
The entire comment is basically making up strawmans... I didn't give practical examples to save space, obviously, it was just to disambiguate what I meant.
TypeScript has several runtime-safe advanced validators based on its type system (most well-known being Zod), capable of enforcing types similar to what I provided.
To conclude, these type system features were added by multiple experienced language designers for a reason, to languages that already had functional ADTs, so going "huh but what are these even useful for?!" to me sounds a bit clueless (or argumentative), so I don't see a productive continuation to this discussion.
> these type system features were added by multiple experienced language designers for a reason
Oooh, an appeal to authority, where that authority isn't even named. I'll have you know a famous queen told me you're wrong on this, also for "a reason".
> TypeScript has several runtime-safe advanced validators based on its type system (most well-known being Zod), capable of enforcing types similar to what I provided.
Right, so TS typing is so amazing it requires runtime parser libraries from NPM, and Haskell is less sophisticated because it's not stringly typed.
You realise the entire, complete, exhaustive runtime schema for your zero-first non-empty integer array example looks like this in Haskell, right?
That's a complete function that somehow manages to work without pulling in NPM dependencies. The best JavaScript minds of our generation remain baffled.> The Person/Wine example is a pointless strawman
> I didn't give practical examples to save space, obviously, it was just to disambiguate what I meant.
So when you use illustrative examples, it is to "disambiguate what you meant" (huh?), and when I do it, they're "pointless strawmen". A little hypocritical, no?
> a bit ignorant
Honestly, I don't think you know what you're talking about at all. You clearly hadn't even read my comment when you started replying with Python and TS examples... that were already in my comment.
It also really sounds like you're using string literals to type input without properly parsing it, which is just a terrible idea. Haskell's type system is designed precisely to protect you from this sort of mistake. [0] No, you're not always going to get what you expect. No, your JS program will never let you know that's the case. No, a sane type system does not require mainlining runtime parser libraries from the biohazardous oceans of NPM. A schema in Haskell is going to be significantly shorter and sounder than anything in Zod, and you don't need a library for it.
As I said above, TS' type system makes sense for a type system bolted onto a dynamic language post facto. TS needs to more tightly link (even mildly conflate) values and types, since it needs to do a lot of clever narrowing to figure out what mad ball of JS it is dealing with at any given time. Haskell does not operate under any such constraint.
> I don't see a productive continuation to this discussion.
Phew. Timesaver.
Of course the irony of all this is that I use TS daily, and Haskell quite rarely.
[0] https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...
Does not seem like this:
> Please respond to the strongest plausible interpretation of what someone says, not a weaker one that's easier to criticize. Assume good faith.
> Personally, I consider all of Go to be a mistake.
You also consider Scala and OCaml to be mistakes? Because all of what I've mentioned also works in a very similar way in Scala.
> an appeal to authority
No, I didn't appeal to authority. It's the opposite - it's statistics. Multiple experienced language designers don't add features later for nothing. For a similar process, see eg. closures getting added to every mainstream language.
> complete, exhaustive runtime schema
Again, I wasn't talking about runtime schemas, but types. I only mentioned runtime as a counterpoint to the false statement that TypeScript doesn't enforce this. Only reducing this to runtime checking is a fallacy, again.
> A little hypocritical, no?
No, they aren't comparable since I wasn't using the examples as supports for an argument of whether X is better than Y. Strawmen involve argumentation.
> read my comment... examples... that were already in my comment
I read it in detail, the problem is you didn't really read my comment in detail, which illustrated both the subtyping and structural typing aspects (albeit trivially, yes), which yours didn't.
> You're also fairly clearly using string literals to type input without properly parsing it
Okay then, the arrogance of this is pretty astounding... You seem to know what I'm doing better than I am!
To be clear, I'm not doing any of that. And I've written Haskell way before I wrote any TypeScript.
Everything I said to you prior to my last message was fairly gentle. I'm not sure what response you were expecting to what you wrote at that point, which was to accuse me of disingenuous strawman arguments and ignorance. Perhaps you yourself would have benefited from a rule refresher?
> You seem to know what I'm doing better than I am
Apparently so! Trust me, it gives me no pleasure, and I'd rather I didn't.
> Again, I wasn't talking about runtime schemas, but types. I only mentioned runtime as a counterpoint to the false statement that TypeScript doesn't enforce this. Only reducing this to runtime checking is a fallacy, again.
My dear friend, this is almost completely incoherent.
I wish to strictly type myself as a function at this point, whereby your messages are my input, and void is my output. Zod, activate!
That Haskell snippet is just syntax sugar for Left(string) | Right(string), which is trivial in any language with unions.
Not clear why it would be an improvement over just naming the alternatives something meaningful, but if you're wedded to Left and Right, go for it.
The C# unions appear to behave like unions, not disjoint unions.
You are correct that this requires support for disjoint unions (aka tagged unions), which Haskell always had and C# will soon have.
As a (bad) trivial example, you could wrap reading a file in this kind of monstrosity:
Now, such an example would be an odd way to do things ( particuarly because we're not actually avoiding the try/catch inside ), but you get the point. Both FileRead(string value) and FileError(string value) wrap strings in the same way, but are different record types, and the union FileResult ties them back together in a way where you can tell which you have.It's more useful implemented a level deeper, so that the exception is never raised and caught, because exceptions aren't particularly cheap in .NET.
A nice balance of language features and legibility.
I knew that enums were really just named integer values and nothing more, but I had forgotten than you can build a perfectly legal enum from an integer out of the bounds of the enum's range. And a switch statement is non-exhaustive. (As I said, it had been a while since I used C# extensively.) What would have been a few lines of code in Rust turned into dozens to try to exhaustively protect against invalid input.
I know C# is a mature language that has been around for decades, but how janky everything feels comparatively really shocked me. I only very briefly played with F# about a decade ago, but my guess is that I could try to pick that up and call F# from C#, getting much better ergonomics with a combination of the two.
These are solved by the new feature described in the article that we're commenting on right now. They're giving us unions and exhaustive switch. Ctrl+F "canonical way to work with unions" in the article to see an example. One of the best parts about C# is they never stop bringing useful features from other languages back home to us in C#. It makes for a large language with a lot of features, but if we really want something, we'll eventually get it in C#.
Other than web tech, what actually is expressive enough?
How? Can you elaborate?
More seriously, it has all the strengths and weaknesses of WinForms and feels about exactly as unfinished and rough as WinForms. I still have to implement custom widgets that i would have expected to be included out of the box. It's nice that it's cross-platform, though with all the rough edges that cross-platform .net still has. It really, truly feels exactly like every C# UI framework I've ever used in the last 20 years: almost good, not quite finished, and takes an amount of effort that is just unreasonable compared to any other language/framework of any age.
I've been a C# dev for most of my career. I have more fun writing UIs from scratch by drawing individual pixels in C++ than any C# UI.
To clarify, these tagged unions are fundamentally different from the untagged unions that can be found in languages like Typescript or Scala 3.
Tagged unions (also called "discriminated unions" or "sum types") are algebraic data types. They act as wrappers, via special constructors, for two (or more) disjoint types and values. So a tagged union acts like a bag that has two (or more) labelled ("tagged") slots, where each slot has exactly one type and exactly one of these slot can take a value.
Untagged unions are set theoretic (rather than algebraic) data types. They don't require wrapping via a special constructor. They behave like the logical OR. They are not disjoint slots of a separate construct. A variable or function x with the type "Foo | Bar" can be of type Foo, or Bar, or both. To access a Foo method on x, one has to first perform a typecheck for Foo, otherwise the compiler will refuse the method call (since x might only have the type Bar which would produce an exception). If a variable is of type A, it is also of type A|B ("A or B"). There are also intersection types (A&B) which indicate that something has both types rather than at least one, and complement/negation types (~A indicates that something is of any type except A). Though the latter are not implemented in any major language so far.
The C# union does not store any discriminator. Just look at the implementation - it's a single `object?` field.
The discriminative part is handled by run-time type information, which is stored in the object itself, not the union - which is why the C# built-in implementation requires boxing.
Also, you can use the same class/record type ("discriminator") in several different unions - again, a feature which ADTs/sum-types/tagged unions in most functional languages do not have.
You can even store one single object (ie. identical by reference equality) in several different union values at the same time, theoretically, which in combination with mutability is... uhh, certainly not common functional/mathematical semantics.
Having these tags be a language construct is just a DX feature on top of unions. A very handy one, but it doesn't make tagged and untagged unions spring from different theoretical universes. I enjoy the ADT / set-theoretic debate as much as the next PL nerd, but theory ought to conform to reality, not vice versa.
I honestly don't even remotely understand how you got to that from what I wrote.
Unions already have a definition. You cannot go around claiming that technically unions are not unions (and that "most people don't know" this), because theory X or Y overloads the term union to refer to some unrelated concept. That's fine and well and good, within that theory, but it does not displace the usual CS definition of union. It is a load-bearing definition.
A tagged union is so called because it is a union (overlapping memory) with a field (a tag) containing a discriminator (aka discriminated union). An untagged union is a union without this tag. These terms didn't come out of nowhere. They are transparent descriptors of what's happening.
It doesn't matter whether Haskell is implemented in C or Ruby, and it doesn't matter whether it's functional, object-oriented, or a DSL for modding Elden Ring, none of this changes what a union is. I'm very supportive of type theories exploring the option space for type constructs, but someone's going to have to implement these somehow. Such as with (tagged) unions. You know, that CS concept we have, with a settled and well understood meaning.
To be fair to you, I think you're letting a very narrow definition of 'union' shadow a much more usual and common definition of the word. And that's totally fine if that's the definition pertinent to you and your work, but if that's the case, maybe don't go around pontificating about how most people do not understand unions?
I never said this. I said that there are two different kinds of unions with quite different definitions and behaviors.
> A tagged union is so called because it is a union (overlapping memory) with a field (a tag) containing a discriminator (aka discriminated union). An untagged union is a union without this tag.
That alone doesn't sufficiently describe the "unions" in set theoretic type systems like TypeScript. As I said, these unions are not disjoint and don't involve the special constructor that tagged unions/discriminated unions/sum types in algebraic type systems do. They also have logical implications like A implying A|B. Or A|A being equivalent to A, which isn't the case for discriminated/tagged unions. Maybe they are implemented similarly under the hood, but that doesn't negate the difference.
Edit: It's probably fair to say that "untagged unions" in languages like TypeScript, Ceylon or Scala 3 (set theoretic type systems) are different from "untagged unions" in C. It only adds to the confusion...
It's hard to know what to say to this. Tagged unions are not tagged unions, even if they are literal tagged unions? What?
I reiterate what I said in my previous comment, you're not using the ordinary definition of the term union, and this is causing confusion. A union may or may not be a "union" as understood within various academic type theories, that really depends on how any given theory defines that word, which can be any way it wants. But a union is a CS concept with a clearly understood meaning, and when used without added context to suggest it is to be interpreted in some theoretical way, it is understood in that ordinary way.
OP's article is clearly using 'union' to mean tagged unions - he even shows off their implementation, with a tag. The author assumes that his audience will understand what he's talking about when he uses the word union, and it's not causing anyone trouble in this comments section. The fact that alternative definitions within various theoretical paradigms is very nice, bless their hearts, but not really relevant.
You may prefer other definitions to the usual CS definition, that's certainly your prerogative, but - again - that's hardly grounds for taking an article and comment section that's using the commonplace meaning, and appearing to lecture others for failing to adhere to your idiosyncratic standards for what a union must be.
It's neither ambiguous nor confusing to use the word union in CS. The only person who's making it so is you, by introducing semi-unrelated concepts from set theory that happen to have the same name as the established CS concept.
Why stop there? Maybe the author meant the Union, as in the United States? Itself quite ambiguous - does he mean the United States of Mexico, or the United States of the Ionian Islands? Is C# getting Corfu? Corfu dot net? :P
Wrong, see this comment: https://news.ycombinator.com/item?id=48251896
Clearly he thought that it's the same kind of union as in TypeScript and that in C# just the syntax is weird. Which is not the case. Some others who are not commenting are probably also not aware of the two kinds of union types (or three, counting C separately).
> It's neither ambiguous nor confusing to use the word union in CS.
Well, we disagree.
> Well, we disagree.
Most people here know the set theory definition of unions. It's simply a niche use, compared to the usual CS definition, which is the one used in the original article and now all the comments.
You're swimming upstream with a definition that doesn't reflect what is under discussion, which you decreed as though from on high, complete with the assertion that most people don't understand unions like you do. They do.
No this makes no sense at all. Set theoretic types don't use special constructors, there is no way to make them look remotely similar. He is clearly not aware that these are different kinds of unions.
> They do.
Nope, precisely because they are less common. You yourself also clearly also didn't understand the difference between "untagged unions" in C and set theoretic type systems.
You have come into a room full of CS practitioners to announce to them that you alone understand what unions are. Never mind fifty years of industry practices and nomenclature - never mind the fact we all already know set theory and unlike you don't confuse set theoretic unions with tagged unions - all that can now be set aside because you discovered set theory last week and now no one understands unions except for you.
Can't wait for next week when you discover some new band, and you'll be in here telling us how no one gets music except for you. :P
Note that my expectation would be that the non-boxed form would be as trivial as adding `[NonBoxedUnion(SomeImplStrategyChoiceEnum)]` (or `[NonBoxedUnion]` for some default strategy choices that likely are ok).
This would give you extremely fine grained flexible choice on how you wanted your non-boxing union to work. There's no single right answer. There are just tradeoffs in terms of space/speed/copying-costs/memory-safety/etc.
I think it would make the most sense as people who care about boxing will have very different views and needs in terms of things like space, casting costs, copying speed etc.
The vast vast majority of users do not need to care at all. And for that, a boxed approach works exceptionally well.
Come on Gophers! It's time.
Not entirely convinced that I see the usecase that makes up for the potential madness.
2001: "Beating the Averages" (Paul Graham) [1]
2006: "Can Your Programming Language Do This?" (Joel Spolsky) [2]
Both of these articles argue for the thesis that programmers that have been deprived of certain language features often argue that they don't need those features since they are already comfortable working around the lack of said features.
It's a fancy way of arguing: you don't know what you're missing because you've never had it. Or, don't knock it until you try it.
Consider, is your argument a) I've never used it and don't see a need for it, or b) I've used it before and didn't get any benefit?
1. https://paulgraham.com/avg.html?viewfullsite=1
2. https://www.joelonsoftware.com/2006/08/01/can-your-programmi...
1. Argue from ignorance. Never try unions in any other programming languages and completely disallow their use in C# codebases that you participate in.
2. Try them out and adopt an informed opinion.
You may even choose to remain in ignorance until someone wastes their own time trying to convince you. But it isn't my job or desire to teach someone who won't put in the effort to learn for themselves.
My primary concern with this pattern versus exceptions is calling code can simply discard the resulting problem.
In current C# I usually do something like
public class ApiResponse<T> { public T? Response { get; set; } public bool IsSuccessful { get; set; } public ErrorResponse Error { get; set; } }
This means I have to check that IsSuccessful is true (and/or that Response is not null). But more importantly, it means my imbecile coworkers who never read my documentation need to do so as well otherwise they're going to have a null reference exception in prod because they never actually test their garbage before pushing it to prod. And I get pulled into a 4 hour meeting to debug and solve the issue as a result.
With union types, I can return a union of the types T and ErrorResponse and save myself massive headaches.
Until your coworker comes along and accidentally refactors the code to skip the exception catching and it suddenly blows up prod.
With tagged unions you can't accidentally dereference to the underlying value without checking if it's actually proper data first.
can't my co-worker just use this pattern and discard an error result the same? I'd argue its easier as the stack wont unwind by default because the error is returned instead of thrown.
Yeah, I'm mildly sold on this use-case to be fair. But I think I'll keep the unexpected errors as exceptions.
As a consumer, you cannot change the methods, but you can add a subtype. When you subtype an abstract class or an interface, the compiler does not let you proceed until you have implemented all the methods.
Discriminated unions are for the exact opposite situation, when you have a fixed set of subtypes, but unbounded set of methods to implement on them. As a consumer, you cannot add a subtype, but you can add a new method. When you write a new method, the compiler does not let you proceed until you have handled all the subtypes.
Good languages should support both!
The best example is abstract syntax trees, the data types that represent expressions and statements in a programming language. "Expression" breaks down into cases: integer literal, string literal, variable name, binary operations like add(expr1,expr2), unary operations like negate(expr), function call(functionName, exprs), etc.
Clearly all of these expression subtypes should belong to a base type `Expression`. But what methods do you put on `Expression`? If you're writing a compiler, you have to walk this syntax tree many times for very different purposes. First you might do a pass on it where you "de-sugar" syntax, then another pass where you type-check it and resolve names in the code, then another pass where you generate assembly code from it. Perhaps your compiler even supports different backends so you have a code-gen path for x86, another for ARM, etc. You'll likely want a pretty-printer so you can do automatic reformatting, maybe you want linting support, etc.
If you look at all those concerns and say that each subtype of `Expression` must implement methods for each one, then you end up with untenable code organization. Every expression subtype now has a huge stack of methods to implement all in one file, dealing with stuff from totally different layers of the compiler. It's a mess.
It's much cleaner to have the "shape" of the expression defined in one place without all that clutter, and then in each of those areas of the code you can write methods that consume expressions however they need, so each of those separate concerns lives in its own silo.
------------------------------------------------
Some real code (but it's F# not C#) to look at.
AST for my SQL dialect: https://github.com/fsprojects/Rezoom.SQL/blob/master/src/Rez... Typechecker code: https://github.com/fsprojects/Rezoom.SQL/blob/master/src/Rez... Backend code that outputs MS TSQL from it: https://github.com/fsprojects/Rezoom.SQL/blob/master/src/Rez...
------------------------------------------------
If you're an old hand at OO you may be familiar with its actual answer to this problem, the "Visitor" pattern. See System.Linq.Expressions.ExpressionVisitor. However, once you've used a language with good union and pattern matching support, this feels like a clunky hack. Basically the mirror image of a language without real object orientation imitating it by passing around closures and structs-of-closures.
------------------------------------------------
It doesn't just have to be compiler stuff. A business app data model can use this too. Instead of having:
You could have: The implementation details of those different auth methods, the UI for them, etc. don't have to be part of the data model. We do have to model what "shapes" of data are acceptable, but "doing stuff" based on those shapes is another layer's problem.Often the explanations just seem rather abstract which makes it harder to appreciate the win, versus the hideous sort of code that might appear when they're misused.
"Make invalid states unrepresentable."
https://fsharpforfunandprofit.com/posts/designing-with-types...
while visiting https://dotnetfiddle.net and typing the code samples in, experimenting with what manner of changes and additions to the code cause the compilation to fail, and considering how you would leverage those abilities in your everyday development work.
I think this would be even more powerful if you then come back and re-read some of the pro-Union comments in this very thread.
"Non-discriminated" unions (i.e. untagged unions) are even less supported. TypeScript seems to be the only really popular language that has them.
such as?
> This should reduce the proliferation of verbose class hierarchies in C#
So just as an alternative for class hierarchies? I mean good people already balance that by having a preference for composition.
The problem with C# is that it’s so overloaded with features.
If you come from one codebase to another codebase by a different team it’s close to learning a completely new language, but worse, there is no documentation I can find that will teach me only about that language.
Throw in all the versioning issues and the fact that .Net shops aren’t great about updating to the latest versions, especially because versions, although technologically separated from Visual Studio, are still culturally tied to it, and trying to break that coupling causes all kinds of weird challenges to solve.
Then stuff like extensions means your private codebase or a 3rd party lib may have added native looking functionality that’s not part of the language but looks like it is.
Finally, keywords and operators are terribly overloaded in C# at this point, where a keyword can have completely different meanings based on what it’s surrounded by.
LLMs are a huge help here, since you can point to a line of code and ask them to figure it out, but it still makes the process of navigating a C# codebase extremely challenging.
So I can see why someone may be unhappy to see yet another feature. It’s not just this one feature. It’s the 100s of other features that are hard to even identify.
I switched between dozens of similar codebases over a period of 3-4 years (pre AI) when I was consulting and did multiple projects in multiple languages (well, only 1 in rust).
In my experience switching between the C# projects was always the worst. The codebase semantics diverged in ways I simply didn’t see in the Java/C++ codebases.
Now this one sounds almost unbelievable :). I’ve yet to see 3 or more C++ codebases using the same language feature set.
I get there's an .Either pattern when chaining function calls so you don't have to do weird typing to return errors, but I'm using exceptions for that anyway, so the return type isn't an issue.
Microsoft C# guidelines recommend try-parse (which is just the Result pattern, albeit somewhat cludgy with no unions) over exceptions.
https://learn.microsoft.com/en-us/dotnet/standard/design-gui...
Compare this to exceptions, where the type is just `T` and can be used without further ceremony. You can discard the error by forgetting a handler. Now you have a program that occasionally crashes.
Follow-up: Are there async exceptions? A `Result` is just data that can be awaited. How would that work with exceptions?
There's not tons of noise being made because for the most part it all, Just Works and that's fairly boring. Perf, memory usage etc gets better every release. As an ecosystem, I'm pretty happy with it. I reach for other languages for smaller microservices.
You mean Raileasy? Or RDG too? (Just curious about the stack of the wider rail tech infra)
It’s a very decent language (I mean C#) and runtime, I wish it had more market share in the startup world.
Rider is definitely the most equivalent to full Visual Studio though.
Godot was using Mono too but has since switched to .NET in version 4.
Still a great language and I hope Unity can hit their target to switch to .NET soon!
All of them run in Linux servers.
Some of them were ported from PHP and Python to C#.
Plus LLMs thrive in strongly typed languages.
Which means C# will keep being very strong in enterprise too. Not only in games where it reigns a large chunk of the market share.
companies spend a lot on marketing, and it's not just ads.