Official proposal for Type Unions in C#
github.com
github.com
I know not everyone likes them, but for typed languages I find it extremely hard to go back to languages without ADTs of some kind. I do Java for my current job, and Java is generally fine enough, but it's a little annoying when I have to do whacky workarounds with wrapper classes to get something that would be done in three lines of F#.
Instead they've been, very slowly, turning C# into F#, which is even weirder to watch.
I miss writing it; I haven't had a job using it in a few years but I really enjoyed writing code in it when I did. Most of my personal projects haven't really been able to use .NET for awhile, so I never seem to have an excuse to play with F# in my personal time.
I never got into C#, so I can't say that I really feel the pain of the C# transition into F#.
[1] At least in the typed world. I'm also really partial to Clojure.
To be clear, it's not like I'm new to functional languages and their type systems, I've been doing Haskell for forever, and I did F# for a multiple years, but Scala has never really clicked for me.
Personally, for doing JVM stuff, I'm a pretty die-hard Clojure advocate. I feel like it's easy for me to write Clojure in the way that I think, while still allowing me to mooch off the entire Java ecosystem, and if there are things that I don't like about the language it's really not that hard to macro in a new feature (though obviously this should be used sparingly).
I definitely recommend giving F# a try. I think it's an extremely underrated language.
Do you have any recommendations for people who do not have C#/.NET experience who want to rip their toes in F#? The last time I tried the language I bumped my head on the .NET parts. :/
For the most part I didn't need most of the built in .NET libraries; the F# stuff was fine, but the ones I ended up using a lot were the threadsafe libraries for when I needed mutation across threads. ConcurrentDictionary was one I used an awful lot, ConcurrentBag occasionally, SemaphorSlim, and Interlocked Incrementors.
The reason that the .NET compatibility was handy to me was because it made it easy to get third party libraries without much fuss, which was great because they were generally pretty well supported.
The rule of thumb that I used was that F#, while it kind of looks like Haskell, is not Haskell, and specifically it's not lazy, and as such I always kind of pretended I was in the `do` block. Things execute top down, and you can mix in side effects wherever, so you kind of have to pretend everything is in an IO monad, or at least if you see anything that has a side effect in there.
[1] I was hired at Jet.com specifically because I had Haskell and Erlang experience prior. I had never written any significant C# code before.
Also, having the documentation split between the F# parts on one site and the .NET parts on another site was a bit of a pain.
It might have gone better if I was starting with a book instead of picking docs off the web.
FWIW I think it works fine with Nix, so if you're not opposed to using that package manager it should pretty trivial to get different versions working with a nix shell and/or flake.
In F#'s case, there are plenty of good books, and then it is really needed to learn the platform.
Some well known ones => Stylish F#, F# in Action, Domain Modeling Made Functional
That was a bit of a surprise - I’d forgotten how expressive Scala is. I didn’t need any “advanced” type system features. But my time to market was literally a couple hours instead of days like with C#, Java, Kotlin, Go, bending to fit the logic into the confines of their type systems. Kotlin is just awesome and very expressive. But it turns out, to me, Scala is somehow very natural - just write what you think, and it works.
Interestingly, that was also my experience many years ago when I first exposed myself to Scala in a numerical analysis class just to avoid Java, and it just worked right away. I recall well that surprised feeling. So I’m kinda happy to move back to Scala now. But I’ll also try to implement the same in F#, right after delivering the next feature set.
From what I've seen, Scala3 is better in this regard (at least the magic part), but I since Spark doesn't support it yet, my exposure to it has been limited.
Thing is the community doesn't reach that often to them.
Something that helps, a ton, is as you're transitioning, you can write code almost identically to how you did before. It doesn't force FP on you at all. It's less useful if you try to do that, because you're not taking advantage of the language, but it makes testing your beliefs on how things work SUPER easy because you can set it up in the OOP way, get the result you expect, then set up in what you think is the correct FP way, and see if it matches.
The only issue is there's a severe lack of beginner friendly documentation (although it's leagues better than it used to be). I honestly think that if you're a C# dev, it's probably worth giving it a weekend or two to play with. ESPECIALLY if you like linq syntax.
I'm not. I find F#s syntax much more pleasing and elegant, and I'm afraid F# will wither away when C# is a watered down version of it.
Still, good to see Java joining the 21st century at least.
Same for C# with this new feature. Sum types (as I like to call tagged/type unions) are such an important tool to have, not having it makes languages resort to all kinds of abominations, e.g. exceptions, product types (= records, structs, etc) that are actually sum types, "null to signify something went wrong", etc.
Not having them from a language's start results in an std lib that does not use them and hence teaches new comer to the language a bad way to do it.
I'm almost of the mind to use F# or C# instead of waiting.
For one, they don't work for generic code where you want to discriminate. I.e., if you have a generic A or B type, you can't pattern match on it. And it's hard to add restrictions to the generic types such that it would work.
Such types sort of work in TypeScript, but TypeScript also has structural typing, meaning that it's designed for it.
Pattern matching too.
This is a weird take, given that Java has had ADTs for years
Records https://en.wikipedia.org/wiki/Java_version_history#Java_16
Sealed classes https://en.wikipedia.org/wiki/Java_version_history#Java_17
And pattern matching for almost a year https://en.wikipedia.org/wiki/Java_version_history#Java_21
Otherwise big agree on how delightful to work with F# is.
Additionally, excited to now watch this go in and people on HN still act like C# is the same it was 10 years ago.
In any case, welcome to C# and thanks!
Just a little bit of patience with the collections, I'm slowly learning to trust the native offerings, at least there's a regular List at the bottom now, much thanks to you.
I'm just used to using more descriptive type names, that's all. It bothers me to no end when I have to keep guessing and memorizing the correct primitive type for a concept. Also makes the code more difficult to read.
I'll have a look at the PR, thank you!
https://github.com/dotnet/csharplang/blob/18a527bcc1f0bdaf54...
Heh yeah well, for better or worse, it seems to be C#’s design goal to have every single feature possible, with multiple variations of each of them. It means it’s able to cater to everyone and doesn’t turn people off the way strongly opinionated languages can. But it can make it a bit tricky to pick up.
I'd really push back against this - where do you see API duplication? IMO the C# team is _incredibly_ conservative with new language features and only add in things that fit a missing part of the language, and when doing so try to also weave in existing C# features to build upon.
I think if anything you may be referring to syntax options? There are a few syntactical ways to do the same things for sure, but I don't think that's bad, as each has their own use. But for bigger tentpole features like records or Span<T> or whatever, they are directly addressing a need and aren't just iterative versions of other things.
Is this just a case of "C# developers like to make up different names than established terminology"? (see: SelectMany, IEnumerable, etc.)
UPD. They have this in the FAQ:
Q: Why are there no tagged unions?
A: Union structs are both tagged unions and type unions. Under the hood, a union struct is a tagged union, even exposing an enum property that is the tag to enable faster compiler generated code, but in the language it is presented as a type union to allow you to interact with it in familiar ways, like type tests, casts and pattern matching. enum Option<T> {
None,
Some(T),
}
The tags are "None" and "Some" which are definitely user facing.But I see what they mean a bit with the C# example:
union U
{
A(int x, string y);
B(int z);
C;
}
So it seems like "A", "B", and "C" are tags but also their own distinct types, with a implicit conversions between those and the overall union typeTake Option<Infallible>, it's a ZST, not only is there no "tag" there isn't any data at all. In type theory this is fine, we added an empty type to the unit type, we got a unit type.
- closed hierarchies of reference types that the compiler will verify at build time
- value types that use compiler tricks to behave like closed hierarchies (tagged unions)
- custom types that can have any implementation but can hook into the same compiler mechanisms to behave like a union of types
- ad-hoc unions of existing types
I’ve never felt like I’ve fully understood the implications of the expression problem https://en.wikipedia.org/wiki/Expression_problem but my best/latest personal hypothesis is that providing extension points via conventional polymorphism might be best suited for unknown/future clients who might extend the code, but unions with exhaustive pattern matching seem better suited for code that I or my team owns. I don’t typically want to extend that code. More often, I instead want to update my core data structures to reflect ongoing changes in my understanding of the business domain, more often than not using these Union-type relationships, and then lean on the compiler errors maximally to get feedback about where the rest of the imperative code now no longer matches the business domain data structures.
OOP Approach with interface/inheritance:
Easy: Adding new types (variants) of a base class/interface. Hard: Adding new functionality to the base class/interface, as it requires implementing it in all existing types.
FP Approach with Discriminated Unions:
Easy: Adding new functions. Create a function and match on the DU; the compiler ensures all cases are handled. Hard: Adding new types to the DU, as it requires updating all existing exhaustive pattern matches throughout the codebase.
Here's some Kotlin code. Kotlin is great because it can do both really well.
// Object-Oriented Approach
interface Shape {
fun area(): Double
fun perimeter(): Double
}
class Circle(val radius: Double) : Shape {
override fun area() = Math.PI \* radius \* radius
override fun perimeter() = 2 \* Math.PI \* radius
}
class Rectangle(val width: Double, val height: Double) : Shape {
override fun area() = width \* height
override fun perimeter() = 2 \* (width + height)
}
// Easy to add new shape
class Triangle(val a: Double, val b: Double, val c: Double) : Shape {
override fun area(): Double {
val s = (a + b + c) / 2
return Math.sqrt(s \* (s - a) \* (s - b) \* (s - c))
}
override fun perimeter() = a + b + c
}
// Hard to add new function (need to modify all existing shapes)
// interface Shape {
// fun area(): Double
// fun perimeter(): Double
// fun draw(): String // New function
// }
// Functional Approach
sealed class ShapeFP {
data class CircleFP(val radius: Double) : ShapeFP()
data class RectangleFP(val width: Double, val height: Double) : ShapeFP()
}
fun area(shape: ShapeFP): Double = when (shape) {
is ShapeFP.CircleFP -> Math.PI \* shape.radius \* shape.radius
is ShapeFP.RectangleFP -> shape.width \* shape.height
}
fun perimeter(shape: ShapeFP): Double = when (shape) {
is ShapeFP.CircleFP -> 2 \* Math.PI \* shape.radius
is ShapeFP.RectangleFP -> 2 \* (shape.width + shape.height)
}
// Easy to add new function
fun draw(shape: ShapeFP): String = when (shape) {
is ShapeFP.CircleFP -> "O"
is ShapeFP.RectangleFP -> "[]"
}
// Hard to add new shape (need to update all existing functions)
// sealed class ShapeFP {
// data class CircleFP(val radius: Double) : ShapeFP()
// data class RectangleFP(val width: Double, val height: Double) : ShapeFP()
// data class TriangleFP(val a: Double, val b: Double, val c: Double) : ShapeFP()
// }However the definitions make the 2 choices (adding new types vs adding new functions/operations) sound like a toss-up.
It is the fact that I tend to find the FP/DU approach so much more frequently useful for my/my team's own code that makes me wonder if I'm missing something.
Perhaps the important distinction I've been missing is in Wikipedia's definition:
"The goal is to define a data abstraction that is extensible both in its representations and its behaviors, where one can add new representations and new behaviors to the data abstraction, without recompiling existing code, and while retaining static type safety (e.g., no casts)."
... but when I'm working on my own/team's code, it is perfectly sensible to recompile the code constantly.
When you are extending, you actually want to choose the correct thing depending on what you need. Going the wrong direction is painful in both directions.
Personally I think one of the reasons sum types are greeted with such "oh my gosh where have you been all my life" reactions is precisely that we had type extension as our only option for so long. If we had had only sum types, and type extension was given to us for the first time in obscure languages 20 years ago and they only really started getting popular in the last 5 or so, I think they'd be considered in much the same way. Just as in a world with only screwdrivers, the invention of the hammer would be hailed as a revolution... and in a world with only hammers, the invention of the screwdriver would be hailed as a revolution. But in both cases the real mystery is how the hypothetical world got that far in the first place.
Not that they aren't useful; consider what it means that I'm analogizing them to something like a hammer and a screwdriver, not an oil filter remover or something. It is weird that we were missing one of them for as long as we were in the mainstream.
Though I do wonder as well how many people encountered them in their "spread their wings" phase and happened to be learning about sum types just as their general programming skill was leveling up in general, and conflate the two. When you learn how to use both skillfully, I really feel like the differences collapse quite a bit. I see so, so much bad code with type-based extension, but it's not because they're using type-based extension, but just that it's bad code, regardless. Of course bad type-extension code is worse than good sum types code, but there's still times and places for both approaches when you know what you're doing with both.
Maybe you can read all the public fields, but you can't actually modify them or create functions that modify the object. You then must wrapper around the instances and fight to bridge every little behavior between their code and yours.
This to me is evidence that one core tenet of OOP "Open to extension" is in-practice meaningless.
https://deliberate-software.com/christmas-f-number-polymorph...
But this looks like a discriminated union which I'd recognise from F# or Haskell. The distinction I'd draw is that for a DU there are named case constructors. Yes?
"sum type" is the term of art in Computer Science theory, but "union type" is also used.
See
sum types also have tagged and untagged variants. the untagged variants are less useful (more cumbersome) in case of sum types and hence often are not implemented in languages.
Not always true in C#. Tuples can have member names
https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
var p = (x: 1, y: 2);
var q = (u: 1, y: 2);
var f = ((int x, int y) a) => a.x + a.y;
then p == q
f(p) == 3
f(q) == 3
p.GetType() == q.GetType()
are all true, but var r = q.x;
yields the compile-time errorCS1061: '(int u, int v)' does not contain a definition for 'x' and no accessible extension method 'x' accepting a first argument of type '(int u, int v)' could be found (are you missing a using directive or an assembly reference?)
and if
dynamic d = q;
then var s = d.u;
compiles, but throwsRuntimeBinderException: 'System.ValueTuple<int,int>' does not contain a definition for 'u'
at runtime, revealing the underlying CLR type.
There is no single "correct name" as there is no single "problem domain" that covers the algebra of type theory, and the pragmatics of programming in engineering, along with other areas.
It does get used to but still reading the too many A|B|undefined gets tiring after a while. It also adds to laziness as you could take one thing and be fuzzy about returning a combo of three or more things. And as you go up the stack this gets more and more confusing.
C# forces you to deal with this in a constrained way which I like.
But perhaps there are folks who are excited by this that have a convincing argument? Please educate me.
I’m pretty sure you can implement the example in this proposal by declaring an empty interface and having some record classes that “implement” it. Does that lose something that I’m not seeing?
Also, the options may not share any surface area at all, so the “interface” for all the types may be empty which is a bit unnatural in OO.
But under the hood, it’s just this: a type hierarchy. But the hierarchy is closed for extension, and (this is the key part you’d not get if doing this “manually” as you describe) when code uses the cases, failing to account for a case will cause an error at compile time.
With an interface, someone could add a new implementation, causing codee to fail at runtime.
I think,.net team haven't added discriminited unions yet because it can be effectively simulated with interfaces.
> Note: Have Mads write this part.
:)
Having _attempted_ (and being bitten by) far too much black magic with C# unions in the past (using FieldOffset), there is an unfortunate situation here: aliasing a pointer/ref value and value is UB. This means that a struct union of a u64 and an object would need separate fields for each, wasting 8 bytes. That is, unless the ryujit/gc is updated with knowledge about this.
It is possible to overlap fields in this way, though offsets occupied by an object reference shall not overlap with offsets occupied by a built-in value type or a part of another object reference.
Per .NET 8.0:
using System.Runtime.InteropServices;
var s = new S { Bar = "Baz" };
[StructLayout(LayoutKind.Explicit)]
public struct S {
[FieldOffset(0)] public UInt64 Foo;
[FieldOffset(0)] public Object Bar;
}
compiles, but throwsSystem.TypeLoadException: Could not load type 'S' from assembly 'foo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.
Interestingly, this code elicits a warning
ILC: Method '[foo]Program.<Main>$(string[])' will always throw because: Failed to load type 'S' from assembly 'foo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because of field offset '0'
from the AOT compiler, but none from the C# compiler.
The C# compiler has very little knowledge of `[FieldOffset]`. It's expected that developers understand the runtime implications of this.
I know I know, pseudo OO took over the world, and then people revolted against it, so the easiest thing to do to stay relevant is to become "slightly functional with curly braces", rather than to actually try and do OO well.
But my question is: what is missing from the OO side? What would it take for C# and/or others to "do OO well"?
As for what C# could do better, the OO solution to the problem pattern matching solves is multiple dispatch - with single dispatch languages you need things like the visitor pattern. Making that a first class part of C# would be fantastic.
https://shawnhargreaves.com/blog/visitor-and-multiple-dispat...
Multiple inheritance. (j/k)
Having "interfaces" and "abstract classes" is just a kludge, multiple inheritance covers all of this with one language construct.
The "diamond problem" is a C++ issue, every other language solved it.
https://learn.microsoft.com/en-us/dotnet/csharp/advanced-top...
CLOS and Ocaml figured it out
Also C++ has exactly what you want. No interfaces, multiple inheritance. People don't utilize it unless it's a GUI lib.
Which concepts or feature you have on mind?
Siamese pet = ...;
(Cat or Chihuahua) mostlyCats = pet;
Dog dog = (Dog)mostlyCats;
Note: This works for implemented interfaces too.I am unsure what that section entails...
Let's say I have a function like this:
void ConsumeAB<T>(T ab) where T: IA, IB;
And implementing classes like this: class ABC : IA, IB {}
class ABD : IA, IB {}
Will I be able to use this function like this: var items = new (ABC or ABD)[] { new ABC(), new ABD() };
foreach (var item in items)
{
ConsumeAB(item);
}
In other words will the ad hoc union act as it would implement all interfaces that all cases have in common? My guess it won't work, as it gets lowered to code that uses object. Would a custom union help me here?Edit: typo
Tearing can cause memory safety issue. Variant A can have an integer field and variant B can have a reference field in the same offset. Tearing can cause it to treat an integer as reference.
At the point where you have more than 5 cases, the GC overhead starts to get shrink in comparison to the calling convention and copying overhead anyway.
I was considering introducing the OneOf library into our codebase, but if this is < a year or so away it might not be worth the effort.
.NET releases are every November, and I would be very surprised to see this in November 2024. More likely November 2025 at soonest. But check back to that page later.
Really though, you don't need a library to do sum-types in C#:
It's best to just use records for now:
public abstract record Maybe<A>
{
private Maybe() { }
public sealed record Just(A Value) : Maybe<A>;
public sealed record Nothing : Maybe<A>;
}
The private constructor and sealed case-types stops anybody else deriving from `Maybe<A>`, so the type is effectively closed and finite.You can then construct like so:
var mx = new Maybe<int>.Just(123);
var my = new Maybe<int>.Nothing();
Then you can use the pattern-matching: var r = mx switch
{
Maybe<int>.Just (var x) => x,
Maybe<int>.Nothing => 0
};
Of course, we don't get exhaustiveness checking, that'll have to wait for the proper sum-types (although the compiler does some pretty good work on this right now); but until then this is the most expressive and powerful way of doing sum-types in C#.And, if you want a load of pre-built ones, then my library language-ext will help [1]
public record UhOh<A> : Maybe<A>
{
public UhOh() : base(new Maybe<A>.Nothing())
{
}
}
Maybe<int> m = new UhOh<int>();I implemented my own option types entirely differently via ref structs where the "non-option" becomes either a default of a value type or a null reference (size of a pointer). Then (in theory) the overhead is reduced to a single dereference with everything else being stack-allocated.
I then built the same thing as a non ref (regular) struct version for storing in a field. So I have Options.Quick and Options.Long namespaces with practically the same struct design just the former is a ref struct.
This has served me very well, is very fast. It just doesn't have the exhaustive checking and risks derefing a null reference, but in practice is not a big issue.
if(option.IsT1){ doSomething(option.ValueT1)};
if(option.IsT1){doSomething(option.ValueT2)}; // this would throw an exception, i.e. a bug, but its very readable to catch the bugUnion types (what the proposal here calls "ad hoc unions") are a separate, much harder feature whose value proposition is less clear. The cost of adding a new kind to the type system is quite large because it impacts method resolution, overriding, type inference, subtyping, least upper bound, generics, type promotion, etc.
It can be worth it (for example, we added tuple/record types in Dart 3.0), but the value proposition must be correspondingly high to justify it. It's not clear that union types meet that bar yet. In many if not most of the places where users are asking for it, it often seems like what they really want is overloading or some other feature.
Related issue: https://github.com/dart-lang/language/issues/83
But for the projects that fall right about in the middle where it could go either way and I could see either language working, I almost always pick rust with discriminated unions being the biggest reason. It's incredibly hard to go back to a language without even basic ADTs after seeing the light.
You're right that it's a second-class citizen.
This isn't true, C# has been adding new ABI features that didn't interact correctly with F# until the compiler and tooling catched up. For example, the spanification of C# was a huge a pain point and it still is when it comes to tooling.
Since its introduction that CLR has the notion of CLS, the Common Language Subset, that any language targeting the CLR should be able to understand.
Anything in the MSIL or metadata, that isn't part of that, requires additional effort from the respective language to be able to expose those features, and many of the more recent improvements, are more in the sense of CLR meaning C# Language Runtime, than Common Language Runtime.
For example, F# used to crash the CLR with InvalidProgramException when setting C# `init` properties. [1] It took almost three years, I think, to release the fix.
[1]: https://github.com/fsharp/fslang-suggestions/issues/904
Another rough example would be spans, and their more general feature, byref-like types (ref struct). These required plenty of compiler support, as they've got special lifetime rules (and more pending to implement `scoped`), they are banned as generic type arguments, and they require ignoring a special Obsolete attribute.
While these were added to F# timely, many language features still break when they interact with them: local functions, computation expressions (even the built-in ones), recursive type inference, and generic intrinsic methods such as `raise`, `defaultof` or `typeof`.
This wouldn't be so bad if C# hadn't "spanified" the shared framework and the entire ecosystem without CLS alternatives for many APIs.
So, these natural F# snippets don't compile:
let numbers = [| for span in text.EnumerateLines() -> Int32.Parse span |]
let checkNonEmpty (span: ReadOnlySpan<'T>) =
if span.Length > 0 then span else failwith "Expected non-empty span."
Edit: And I haven't even gotten into the libraries that use reflection expecting you to declare types in ways F# doesn't support.Generally though, it's pretty easy. Sometimes you'll want to make bindings around various things (not that you need to, but it'll make things smoother).
It's not actually awful, it's just that there's no real documentation of "hey today we're going to take Serilog/whatever and show you how to configure it in F#" style videos, so depending on where your weaknesses lie it can feel frustrating.
Try doing WinForms in F#...
Adding F# to the game would only complicate the scenario, because I would need to connect the F# interfaces somewhere to C# anyway, requiring an additional layer of mappings in many cases.
F# doesn't really buy you anything if you're already invested in C# (or even VB.net for those poor souls) unless you have a very specific use-case for it, IMO.
Every time I try to use it I'm left with a feeling it's not worth the hassle over C#.
C# has been quite nice for 10 years and they keep improving consistently with every version.
You're going to have patterns from the .NET Framework era being ported to .NET Core projects. It works, but you'll have two paradigms of doing things mixed into your project.
I envy people who only do hobbyist C# so get to work on code bases that have all the newest language feature usage.
But when you have to work on "diverse" development teams having some sort of patterns established (flawed as they are) brings some order to the insanity.
I think abstraction bloat is one of those things that's a preference. What's bloat to one is organization to someone else. When I hope into a python codebase and it's 900 line file doing computer vision madness, I hope and pray for abstraction bloat. I'm sure there are countless c# bloated codebases but I think that's mostly a function of c# codebases being inside megacorporate or government codebases. The bloat comes from the general inefficiency that those companies run at. I guess the same could be said by the scrappy python startups that put everything in a single file with no types or inversion of control or OOP.
I guess I'm saying that I'd rather deal with the bloat problem than the wild west problem. lol
You kinda have to fight against the IDE to not do a lot of things a certain way. For example, it'll automatically namespace new files according to your folder structure. They've also turned a certain amount of automatic linting on to gently suggest/nag you to write in a particular way.Suggest you write classes in certain ways, use newer language features, declare variables in better ways, etc. You can ignore all the nagging, but it's also incredibly easy for the next programmer to walk in and use the quick actions functionality to 'fix' the code in a few clicks.
And the asp.net core team have been incredibly opinionated, forcing a lot of good coding practices on the community.
So on the plus side, they pretty much forced DI to be the way we all work now. It's worked really well. Most library authors have now embraced it with gusto and you'll have a hard time using new libraries in a code base that's DI incompatible.
The bad side is that sometimes they made bad choices, but they are more minor things. Like they bizarrely went all in on JWT tokens which work really badly for corporate apps. Or the IOptions pattern for global settings which sucks compared to normal env variables in any other language. Lots of confusion over how they work on forums and SO.
This is why I find a .editorconfig file to be incredibly helpful.
( I'm someone who deals all day with legacy .Net framework projects, mixed with the kind of mix of .Net core 3, .Net 6, .net standard 2.0, and .Net 8 projects that you'd expect from a 20+ year old company with 260+ projects. And yes, I too envy hobbyists at time. )
Overriding equals to do memberwise comparisons on POCOs
Any checking of types where pattern matching would be better
Old-style tuples without names (old style is tuple.Item1, tuple.Item2, etc.)
Checking of multiple tuple values at once without pattern matching
Any code that could be refactored with the new LINQ methods
Long ifs/switches that could be replaced by pattern matching
Concatenate a lot of strings (one per line) so there wasn't a ton of horizontal scroll, particularly for SQL in C# code
using statements still needing a level of nesting
I've been spending the past couple years migrating various platforms from Framework to the new .NET and as long as you've got a head on your shoulders it's not too bad. Also, new projects in .NET are fantastic to work with, imo.
It forces you to reconcile your architecture as it gets bigger and before you accidentally turn it into a monolithic nightmare. IMO, It's more than just a preemptive defense against cyclomatic complexity. Going into unfamiliar F# code, the file ordering is usually a huge clue where to start reading first.
We've created very large scale applications in it requiring significant throughput. One of its benefits is also its disadvantages - we typically are quite productive in it and so don't feel the need to hire as many people in the team. Before LLM's were a thing we found we were wasting less time with boilerplate in general than our C# code for example. YMMV.
Its a shame, they even had a second change when Oracle bought sun and no one knew what was going to happen with Java, but fumbled that as well.
pkg install lang/dotnet
Note that not everything will work, and it is community-supported. But the effort is there, and there are contributions to dotnet/runtime from time to time to further improve or fix it. It's in a better state than it was 2 years ago.That statement was true - until 2016. Times change, Microsoft changed.
There's not a single widely distributed infra application in C# out there. When people want to build stuff like kafkas, kubernetes, consuls, they still go to Java/Go/C++.
Java is frankly a bad choice for that too these days for a new project, and for the same reason: why would you develop infrastructure in a language that requires shipping a runtime when Rust and Go exist? That made a lot more sense back when C/C++ was your only other real choice.
Meanwhile, plenty of people are in this thread telling you that they do in fact use C# to distribute cross-platform applications, but you seem to be uninterested in hearing that.
https://devblogs.microsoft.com/java
https://www.microsoft.com/openjdk
https://code.visualstudio.com/docs/languages/java
Because it turns out, making Java running on Azure, on those 60% Linux workloads, is lot of money.
Also plenty of Azure, anything CNCF related, is mostly Go and Rust.
Which is kind of sad, I would expect Azure to be a good contributor for having a .NET presence in the CNCF project landscape.
C# is also fine for this, just way less popular. Recently ms put out https://github.com/microsoft/Garnet when the redis debacle happened.
The Apache project has helped put out quite a few large infra projects, most of them in Java (I don’t know why this is but assume they have lots of resources to help with that, and also that people don’t like debugging memory crashes).
Ms has just been not the greatest collaborators with their open source community. A lot of the time it seems like they want to do the initial foundation, then leave “drawing the rest of the owl” to the community, which ends with lots of partially functional things. GUI frameworks, f# tooling, drivers for commonly used critical infra. At the same time, people get upset when ms tries to build a better version of an existing open source project, so there’s no winning. They’ve just put themselves in such a poor spot.
If you try to install any of the latter, it will be apparent why. (They are poor in usability).
Azure has entered the chat.
Microsoft Orleans has entered the chat.
ASP .NET Core has entered the chat.
Ever played Halo online?
Used StackOverflow? (very likely)
Visited any website on Azure? (most likely)
Microsoft Orleans (Virtual Actor framework) powers the Halo server infrastructure since at least 2011 if not sooner, which arguably the Halo series is insanely popular, especially for online gaming. Also powers plenty of Azure itselfs own infrastructure. I've worked on dozens of scalable C# projects, and know plenty of devs from all over who have as well.
Orleans was so good, EA made their own version in Java which was extensively used there as well, though it looks to be dead, but Orleans is as alive as ever.
Not to mention plenty of Azure itself is open source, like say... Azure Functions, which run inside of ASP .NET Web Services... and are... you guessed it, C#. Plenty of services running on that platform.
https://visualstudiomagazine.com/articles/2018/08/22/bing-ne...
No-one's writing a database server or identity management system or source code repository or business intelligence tool or even something like a linter in cross-platform C#. Unless you're a Windows shop, it's just not a first-class ecosystem.
C# as a language has always been cross-platform.
Though the last few versions have made incredible gains in performance optimizations. You won’t get the flexibility of C++ but the performance comes close to it in most cases, when written optimally.
And you don’t have to deal with arcane, bullshit build systems with a learning curve that is worse than the language, and breaks down on every OS major version update (or its own version updates).
Not really. Like, it notionally ran on FreeBSD, but nontrivial programs never actually worked until recently, and even now they mostly still don't.
We are talking about the language, not the runtime implementation.
pkg install lang/dotnet
Not everything works, and support is community-maintained, but “mostly doesn’t run” does not reflect actual state of affairs.As a sibling comment pointed out, .NET assemblies within Nuget packages are by-definition portable, unless they use platform intrinsics without a fallback and or without using newer crossplat APIs, but this is predominantly specific to SIMD code and a rather niche case that concerns my work.
There are some Nuget packages which come packaged with native dependencies, and some of the ancient and unmaintained ones do come with like a single win-x86 .dll inside, but this is a "things you sometimes encounter with C/C++" and in general is a rare occurrence.
Nowadays, the packages that have native dependencies either simply expect the host to have them installed (like you install, say, gstreamer), or come with dependent packages per-platform (and the matrix gets quite big: [x86, x64, arm64] x [linux, osx, win]). Like https://github.com/sandrohanea/whisper.net
But then again, this has to do with a specific package and its owner, if that's what you meant.
Note that there is no culture issue, there is poor framing and a strawman one. "I had issues on a niche target" is not mutually exclusive with cross-platform. Would you say lack of support for SunOS is a damning evidence of "pro-windows agenda"? (whatever it is, I use macOS and Linux hosts mainly and surprisingly and funnily enough, there is work to support SunOS as well)
The thinly veiled "but linux/unix!" low effort replies are unfortunate and tiresome. They don't strike me as a productive attitude that seeks to make things work.
Not a specific single program (not package) just my general experience of how "find useful-sounding program written in C#" -> "download it, try to run it" usually goes. I could probably dig up the name of the most recent thing I tried it with if you really want (I think it was a video renaming tool) but there's no useful discussion to be had about what a random 1-person project happens to support or not.
> But then again, this has to do with specific package and its owner.
> Note that there is no culture issue, there is poor framing and a strawman one.
If most package owners act a certain way that's what culture is. I doubt either of us has the time to do a statistically valid survey of what's out there. Maybe your experience is different, but let me ask: are you actually using C# programs on non-Windows, and e.g. reporting bugs in them? And finding maintainers take them seriously when you do?
> Would you say lack of support for SunOS is a damning evidence of an anti-OSS culture?
I think projects that assume the whole-world is Linux and don't support e.g. FreeBSD or Illumos (I assume that's what you meant by SunOS?) are very much anti-OSS, and complain loudly about them when I encounter them, yes. Obviously there are levels of "not supported" here, but "well, your patch sounds ok so I'll merge it, can't promise we won't break FreeBSD again in the future since we don't have the resources to test it" is still better than I've gotten from most C# projects when I've tried.
What is the name of the software that you expected to run on the OS of your choice? I briefly looked through your Github profile hoping to find it but it seems it mostly consists of Scala, Java and a few other non-.NET projects. I assume you haven't had the opportunity to use .NET tooling yet. Are you interested in getting .NET SDK to run on FreeBSD?
Was "the evil" software just an ancient WinForms application?
I've used it some, not to the same extent, and generally at work - another one of those cultural differences I've found is that most JVM/etc. companies are at least theoretically on-board with open-sourcing their non-core libraries, whereas in .NET land there's much less willingness to do that. The actual tooling is good (the best I've used in some ways), but that's only one piece of the puzzle.
> Are you interested in getting .NET SDK to run on FreeBSD?
The SDK itself runs great. I'm more interested in being able to drop in a small program that solves a problem for me - like, that's the way I started with Ruby or OCaml or Go or Erlang, there was a standalone thing that I could pick up and use as part of my system, I didn't have to rearchitect everything or buy into the whole ecosystem or change my workflow. I don't even know Erlang at all, but it's running in my stack in that I'm running Riak (with the Java driver), and that gives me a place where it's already adding value and I could dip my toe further into it if I wanted. That's the thing I've never found from the .NET world - a reason to run it in my system that doesn't require me to fully buy into it to get started. (I guess in theory SQL server could be that, but it's non-opensource and doesn't have any compelling selling point over the substitutes. Part of it's honestly probably just marketing, but that goes for any new language/tool - the most persuasive thing is hearing other people having success with it in a similar situation)
> Was "the evil" software just an ancient WinForms application?
Quite possibly, but I remember command-line tools also not working - just these random one-developer tools have no reason to publish versions for other platforms, and it's not the natural workflow, so they don't. Probably the issues are minor (like, I remember one that was using some windows-only part of the standard library to do something incredibly basic like base64 decoding - I'm sure someone who uses .NET every day would take 30 seconds to swap that out with using the right part of the .NET core standard library instead. But it doesn't make for an easy onramp)
Yes, I do, but only those that I personally encounter, which almost never happens, my daily driver is macOS but .NET treats it very similarly to Linux. Linux is the most well-polished platform though. I can't actually believe we still have to have this kind of conversation in 2024. It's like talking to a street madman who keeps asking "no but is the sky blue? are you sure?". Yes, it is.
And no, it's not something you have to actively think about - just send an http request, write to a file, render a button with avalonia, etc. None of these require thinking about underlying OS. It just works.
In fact, the first version which was called back then .NET Core 1.0 was released 8 years ago, and was already cross-platform. By the time .NET Core 3.1 got released, it was battle-tested and stable, many businesses were moving their applications to linux hosts, often to containerized deployments at the time. This was about 5 years ago. A blink of an eye for enterprise, but a long time ago given the development pace.
> Obviously there are levels of "not supported" here, but "well, your patch sounds ok so I'll merge it, can't promise we won't break FreeBSD again in the future since we don't have the resources to test it" is still better than I've gotten from most C# projects when I've tried.
FreeBSD support is "well, your patch sounds ok so I'll merge it, can't promise we won't break FreeBSD again in the future since we don't have the resources to test it". There are considerations to not break community-supported platforms though.
> I think projects that assume the whole-world is Linux and don't support e.g. FreeBSD or Illumos (I assume that's what you meant by SunOS?) are very much anti-OSS, and complain loudly about them when I encounter them, yes.
I'm sure maintainers appreciate it and are grateful for this kind of attitude :)
I mean, it's the same experience for me the other way round. Every few years someone tells me "yeah, .net works properly on non-windows these days", I file that away in my head, a while later I stumble across a C# tool for something I want to do, I try to run it on my machine, and it doesn't run.
Like, I do believe it's getting better - one of the things linked in this thread actually had Linux installation instructions in the README, which is the first time I've seen that - but in most cases there's no real push or reason to move. It reminds me of the move to Python 3, which didn't really gain momentum until 3.4/3.5 when there were new features that gave an actual motivation to switch.
> In fact, the first version which was called back then .NET Core 1.0 was released 8 years ago, and was already cross-platform.
Yeah, I remember the excitement of that happening, and then the awkward realisation that no existing .NET software was compatible with it. MS pushed out SQL Server remarkably quickly, but there was never really a reason to run it (and while I don't know their nominal support status, it certainly never felt like a first-class platform) and they didn't really follow through. E.g. I don't think Visual Studio proper ever made it over?
> By the time .NET Core 3.1 got released, it was battle-tested and stable, many businesses were moving their applications to linux hosts
OK that is more interesting and promising.
> I'm sure maintainers appreciate it and are grateful for this kind of attitude :)
Meh. Linux monoculture is just as bad as Windows monoculture, the point of open-source is to make it so that people can actually modify and improve your work and use the modified versions, not to publish the code and call it a day.
> No-one's writing a database server
RavenDB, which can be run in a cluster, and uses less CPU (and I've read memory) than MongoDB itself.
There's also a recent C# based redis drop-in replacement that outperforms redis.
See more: https://github.com/quozd/awesome-dotnet?tab=readme-ov-file#d...
As for identity, you sound really silly when you consider it is literally built-in to ASP .NET itself, and can be expanded upon to your hearts desire, plus there's no shortage of available identity management libraries in C#.
As for source code repository, I'm not sure what you mean, but for years Microsoft hosted CodePlex which was essentially GitHub for C# projects. Visual Studio and C# projects are typically hosted on Git, I would be shocked if there's no web UI for git in C#, there's definitely plenty of applications for git in .NET
I'm not even going to comment on business intelligence, now you're just being very lazy. You're telling me Microsoft has 0 BI tooling and SDKs? Come on.
As for a linter, you are either trolling, or just blindly hate Microsoft for no rhyme or reason, there's more than enough linters, especially the best one of all, ReSharper, which is integrated into Rider which is a cross-platform IDE. There's also MonoDevelop, SharpDevelop, etc
I literally spent a few weeks ago porting a .NET 3.5 app I hadn't touched in years, to .NET 8 from Ubuntu Linux, and got it running, in under 30 minutes in Project Rider.
Also nearly forgot. Netflix's original web UI was Silverlight, which is C# / .NET back when it was at its peak for its time.
Ok, that actually sounds interesting. Still haven't heard of anyone using it, and closed-source makes it a non-starter, but I'm vaguely interested. Even then though, sounds like their client libraries are only .NET?
> As for identity, you sound really silly when you consider it is literally built-in to ASP .NET itself, and can be expanded upon to your hearts desire, plus there's no shortage of available identity management libraries in C#.
Sure there is plenty of support for it within the platform. My point is no-one's writing their organisational SSO system in C#, unless they're already bought into the Windows stack.
> As for source code repository, I'm not sure what you mean, but for years Microsoft hosted CodePlex which was essentially GitHub for C# projects.
I mean the equivalent of Bitbucket Server or GitLab, the thing you'd run to host your own source repos internally.
> I'm not even going to comment on business intelligence, now you're just being very lazy. You're telling me Microsoft has 0 BI tooling and SDKs?
No, I'm saying that what they have is all locked into the MS/Windows parallel world stack. There's nothing that a company that isn't committed to them would use.
> As for a linter, you are either trolling, or just blindly hate Microsoft for no rhyme or reason, there's more than enough linters, especially the best one of all, ReSharper, which is integrated into Rider which is a cross-platform IDE. There's also MonoDevelop, SharpDevelop, etc
There are plenty of linters for C#, sure. But no-one would write a general linter in it. It was an example that came to mind because that was how Facebook first started adopting OCaml - a linter is a small standalone tool, so it's an ok place to experiment with a new technology stack.
> Netflix's original web UI was Silverlight, which is C# / .NET back when it was at its peak for its time.
And look how that worked out for them.
Worked out pretty well to be fair, their old UI actually worked perfectly on Linux via Moonlight. Moonlight was more usable than Flash on Linux which was an unstable mess.
> There are plenty of linters for C#, sure. But no-one would write a general linter in it. It was an example that came to mind because that was how Facebook first started adopting OCaml - a linter is a small standalone tool, so it's an ok place to experiment with a new technology stack.
Except ReSharper lints for other things too.
> I mean the equivalent of Bitbucket Server or GitLab, the thing you'd run to host your own source repos internally.
That was CodePlex, there's also Azure DevOps? Which does all the things BitBucket and GitLab do and probably more? It is arguably poorly named in my view, since I've heard managers confuse "DevOps" and "Azure DevOps" by using the term interchangeably.
Up to a point - it lints the things you might need in a C# application. But it's very much a tool for the MS/Windows/C# vertical - even using it in Rider isn't really their focus. If JetBrains was building the linter they used for all IDEA-family IDEs in C#, that would be interesting.
> Azure DevOps
Right, that's the kind of thing I'm talking about. Is anyone using that who's not already bought into MS/Windows/C#, is that a market they sell to at all? Can you even run it on anything other than Windows? It sounds like not, which rather proves the point.
"microsoft didn't really care much about building a community or getting it to work natively in other OSes/toolchains" still rings true IMO. C# has some great stuff if you're fully onboard with the MS stack, but they've taken at most baby steps towards fitting into other environments. (If anything it feels like they expect the rest of the world to fit in with them - if you want to bring e.g. Postgres into your MS/Windows/C# world that's relatively well supported, but going the other direction is much less so)
Moreover, the ecosystem mainly gravitates to Roslyn analyzers which run within build system and, naturally, integrate with Roslyn LSP. They work regardless of IDE or text editor you choose.
In fact, quite a lot of them come out of box, with the basic set enabled by default to prevent you from obvious mistakes, automatically fixing code to use terser syntax or avoiding footguns when using low-level APIs where applicable, and a lot more opt-in for a specific scenario or a workload.
If you’ve used Wi-Fi in a hotel it’s very likely you’ve used a C# app. Is that “infra” and “widely distributed” enough?
Also .NET has been about "run everywhere on any platform" as their tagline for quite a few years now.
They have had plenty of community fumbles without question. I can't speak to those though. I've seen lots of vocal high up Microsoft employees try to win those fights on the side of the community but no idea what happens internally.
A very common modern setup is PostgreSQL, C#/.NET, Linux & using JetBrains Rider for the IDE
You just described the startup I'm at. All devs are on Arm64 MacBooks and we deploy to Arm64 AWS T4g Linux instances. I'm all VS Code, others are primarily Rider..NET is a highly underrated platform for backend; it always puzzles me when teams think about moving from TypeScript to Rust or Go instead of C# because it seems a much smaller leap from TypeScript.
I guess the grass is always greener somewhere
Rust is interesting but the compile times aren't great.
How did we ever prioritize implementation inheritance over ADTs?
I don't know, but it was a mistake.
Like algebraic data types, multiple inheritance wasn't novel, but what were the big famous languages from that time which showed this was a must have for Bjarne's language?
It's not about what was popular, or that Stroustrup was at Cambridge not Edinburgh (all the exciting Programming Language theory stuff in that era like ML was from Edinburgh as you perhaps know). If ADTs were easy, C++ would have ADTs.
The idea would've been well understood, but if the goal of C++ was "C with classes" or more accurately "C + Simula" then it just wasn't part of the goal. And of course we got 20 years of essentially forgetting that sum types existed outside of ML languages until they were "rediscovered"
And I think the answer has a lot to do with the expression problem [1] and which kinds of extensibility were needed in the kinds of programs that languages at the time were designed for.
OOP with subtyping and virtual dispatch makes it very easy to define an interface with a set of methods, and then have an open-ended set of concrete classes that all reliably implement those methods. It makes it easy to say "I don't know what data types I'll need yet, but I do know what operations I'll need."
ADTs flip that around. That make it easy to express "I don't know what operations I'll need yet, but I do know what data types I'll need."
For the kinds of simulations that Kristen Nygaard and Bjarne Stroustrup were writing, and then later the large GUI applications that C++ users were building, it seems that the former was more useful than the latter.
[1]: https://journal.stuffwithstuff.com/2010/10/01/solving-the-ex...
Dynamic dispatch is for a fixed set of operations and open-ended data.
ADTs are for a fixed set of data and open-ended operations.
- https://github.com/domn1995/dunet
- https://github.com/mcintyre321/OneOf
Quite good and ergonomic with the source generators removing a lot of the boilerplate.
I have a practical example here using OneOf with .NET Channels: https://chrlschn.dev/blog/2024/07/csharp-discriminated-union...
https://fuqua.io/CSharpRepl/ For one
For instance, I use throwaway files instead of REPLs, even when I have access to one. I'm still running small and isolated experiments to build my understanding, but I get to use the editor I'm comfortable with and it's easy to copy the code into my project afterwards.
The other thing I used to use REPLs for was introspection/looking up documentation, which my LSP handles nicely. You can think of the LSP as a sort of REPL integrated seamlessly into the editor; when I have a question, I'll query the LSP by writing a line of dummy code that causes the LSP to generate an annotation with the answer. So for instance if I want to know if `foo` implements a certain trait/interface, I can write a variable declaration like `let x: Box<dyn MyTrait> = Box::new(foo)` and see if my LSP annotated that as a type error. I can do this very quickly and without leaving my editor, so it helps me stay in the flow of things.
And *nothing* gets even fucking close in terms of productivity to C#.
Great language, mature and robust ecosystem with sane compilation times and
great tooling: package manager, test runner, strong debugger, one CLI with almost all tools needed.
I wish C++ was half as enjoyable as C# is.
But yeah I think C# is often unfairly viewed as a boring enterprise-y language when it's actually become a very comfy swiss army knife.
Which means anything you write with it can't be included in any distribution.
It's quite limiting. Basically it's only useful for proprietary software shipped by 3rd party.
Quick search shows that SDK and runtime packages are available in the official feeds for
Archlinux: https://archlinux.org/packages/?sort=&q=dotnet
Fedora: https://packages.fedoraproject.org/pkgs/dotnet8.0/
Ubuntu: https://pkgs.org/search/?q=dotnet
I always wondered what is the motivation behind the negative comments like these on .NET submissions. Is this because .NET is mostly made by MS employees instead of Google (which is an AdTech company) or Oracle (which has a license trap JDK distribution)?
This is the motivation ↓
apt install dotnet-sdk-8.0
Error: Unable to locate package dotnet-sdk-8.0
Error: Couldn't find any package by glob 'dotnet-sdk-8.0'JIT: dotnet publish -p:PublishSingleFile=true -p:PublishTrimmed=true
AOT: dotnet publish -p:PublishAot=true -p:OptimizationPreference=Speed*
Use -o to specify destination.
By default targets the host's OS RID, but can be overriden with e.g. `-r linux-musl-arm64`. Cross-architecture compilation is supported within OS, and there is a nuget package that switches the publish to Zig toolchain to allow publishing for Linux under Windows without relying on WSL2: https://www.nuget.org/packages/PublishAotCross This only concerns AOT as .NET uses the same linker to produce the final binary as your regular C/C++ code. It is a true native executable through and through that is understood by all standard tooling like native code profilers. For JIT binaries, anything that .NET supports can be published for under any other OS and ISA.
* my recommendation as the size impact is negligible but codegen quality in edge cases improves quite a bit. Other flags that may be useful are -p:IlcInstructionSet=x86-x64-v3 (AVX2 and friends) and -p:IlcFoldIdenticalMethodBodies=true (it's disabled by default because it can mess up stack traces, naturally, in .NET 9, disabling stack trace information enables it as well).
Which is not distribution friendly. Thanks for finally understanding you were wrong all along.
Why is that?
I've developed on Ubuntu and Pop_OS! in C# for years and never hit a problem.
sudo dnf install dotnet-sdk-8.0.
sudo apt install dotnet-sdk-8.0
sudo apk add dotnet-sdk-8.0Works like a charm.
Any more irrelevant things to say?
The fact that it's not there (and it can't be there) was exactly my point.
I use toilets normally. I don't throw excrements.
literally first link under "dotnet debian" is:
https://learn.microsoft.com/en-us/dotnet/core/install/linux-...
__________
wget https://packages.microsoft.com/config/debian/12/packages-mic... -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb
sudo apt-get update && sudo apt-get install -y dotnet-sdk-8.0
C# gets compared to java a lot for a good reason, and yet the languages and ecosystems have since diverged in their priorities and abilities. This gets even more complicated when considering F# and Scala. Do you think Java would offer similar productivity, or are there aspects to the C# that are—in your personal experience—uniquely productive?
- IntelliJ knows exactly what version of Java you want to run and develop against.
- Async is also trivial. Just fire off a virtual thread.
- it sounds like your company just picked a bad orm. Any good one is going to escape sql injection when binding variables. You are using binding right? If you to “write it in Java” there is also jOOQ.
The one thing I do think C# is far superior at is packaging and distribution. It’s beyond simple to package a C# application into stand alone binary, whether is be AOT or JIT.
1) default C# IDE is junk compared to IntelliJ 2) Gradle give you insane level of control over project you can even build dynamic template tasks shown in IntelliJ UI using Kotlin/Groovy 3) JVM ecosystem is much bigger and default framework SpringBoot is ready to use with houndreds of integrations which are either non existent or hards to use in .NET as opposed to SpringBoot where you have batteries included approach e.g. want outbox pattern? Simply use modulith, convention over configuration will give you some nice defaults… 4) There are plenty of widely used langs compared to .NET if you don’t like modern Java (which is on the same level as C# IMHO) you have: Kotlin which is a better lang than C#, Scala, Groovy from the mainstream ones and Clojure and probably many more lesser known. 5) There is nothing as expressive as Groovy Spock for testing in .Net world.
There are issues I see but can be easy mitigated e.g. I don’t like default Java heavy ORM (especially mapping complicated two way relations) but it’s very easy to not use them and simply relay on mapping foreign key.
To sum it up I bet your issues are mostly you don’t know ecosystem well enough.
Compared to old VS: First and foremost: feature richness of refactorings, code inspections and plugins - basically in the IntelliJ you have everything Reharper plugin can do for .NET and probably more. Second IntelliJ can run on non-spying operating systems. Third it's much more resource friendly for bigger projects. Last but not least ItelliJ is keyboard user friendly (e.g. you can jump and resize windows using only keyboard).
Can't say much about vscode vs IntelliJ. When I tried it last time Java plugin was not there. I could not use ItelliJ keyboard shortcuts - also code formatting and refactoring options were worse than in the itelliJ. That's to be expected it's paid product after all.
I've never used visual studio before so I assume the comparison is going to turn up a different set of issues. However, being tied to windows is probably not a good thing in the long term.
What would you suggest I do to be productive with C#?
That said, in an enterprise setting, for all of Microsoft's other faults, C# is damn near bullet proof. Some enterprises, like mine, can't rely on community supported tooling for life-critical systems. If something breaks, we're near instantaneously on the phone to a dedicated support rep to fix the problem.
I learned C# and Java years ago during my IT degree but had long since forgotten them. The enterprise I work in uses C# a fair bit.
Only started to pick up C# again in the past few months, and holy heck, I forgot how pleasurable it is to work in C# again.
If the third-party components used in some software I help maintain supported JetBrains Rider, I'd use it in a heartbeat.
Visual Studio (not Code...) is okay, though I'm not tripping over myself to use it. PyCharm and IntelliJ have spoiled me.
From a demand standpoint everyone uses the Microsoft variant because it's easy to use and hire for. There's a ton of documentation. Lots of issues are at the seems of different libraries, applications or frameworks you use. And in the Microsoft world it's frequently all the same. Everyone uses the same identity library, the same webserver, the same cloud, the same database, the same orm.
If you're into learning technology it's not for you. But if you're into learning about domains and business instead of tech or like having free time it's a great stack. Doesn't work well for b2c because of the cost, but works really well for b2b.
C# and dotnet are open source so what on Earth are you even talking about?
>squash my curiosity
Maybe increase your curiosity and try something new, change the 15 year trend and use an IDE. JetBrains Rider is great and cross platform.
"tolerance in that community for people who have those values"
More likely is they don't worry about this nonsense and just get work done, making a great language, platform and tools used extensively and productively in many companies. Why should they "think about you at all" as the meme goes?
Talk of culture, values, community, tolerance, "your characteristics". This all reeks of injecting extraneous personal feelings where they don't need to be. How about you just try the language, if you actually care to do so, and worry about the rest later?
Funny enough, it's the efforts of Omnisharp and the VSCode team that has so significantly improved the experience of using various other languages in open source editors due to the creation of LSP.
Beyond that, no offense but I don't think C# devs don't owe you anything, it's on you if you have criteria that excludes you from using all these awesome things.
If your religious beliefs are a sticking point, then so be it.
But this is rather silly, so I'm going to assume the question is more reasonable "What can I do as a Linux user to have positive experience with C#?".
In this case, the response is very simple - you just install the SDK (sudo apt/dnf install dotnet-sdk-8.0) and then pick either VS Code and base (and free and MIT) C# extension (you do not need DevKit) or combine csharp-ls and Neovim. Other text editors that support LSP will also work. Nothing else is required.
Rider is suggested but it is absolutely optional, especially if you are not looking for that kind of high-tier IDE and prefer simpler (and faster) text editing experience.
I've only begrudgingly moved to C# over the last few years as my primary since MS has pretty much killed VB.
Most of those products have the words "Visual" and "Studio" in the name.
Atmel Studio can come too.
What I’d love to see is a hybrid between C# and Rust that has the capabilities of both languages in “layers”.
So business logic would be written in a simple GC variant of the language that feels like C# but the underlying standard library and low-level packages could use Rust-like semantics.
This is already the direction that C# is moving in: it’s getting more and more features related to “ref” and other low-level primitives.
Sadly Rust and C# have fundamental incompatibilities such as different string encodings, so they can’t be directly merged.
If this feature were implemented, it would take C# to a top contender for a daily driver language for me, and would make me feel a lot more confident in choosing it for projects where the C# ecosystem is already present, such Godot's C# version.
I'm really excited about this proposal, and I don't know anything about C#'s development pace, but I'll be watching from the sidelines hoping I can use union types in production in 2025 or so.
You mean like this?
> A proposal for type unions (aka discriminated unions) in C#.
Discriminated unions are a type of union type, hence the name, and in terms of how they're used in everyday development they fill a very similar role. If they have no intention of supporting pure TypeScript-style unions (which I'm sure they don't) then I don't know what the harm is of shortening "discriminated union" to "union" in the context of C#.
Which means the fact that some look at a language level like a traditional closed sum type, and others look more like a union type is pretty much just that, looks. Even the "ad hoc unions" are basically functioning as sum types here, just an ad hoc sum type whose type constructors are other types, and abusing the fact that classes or boxed structs all have a vptr that can be used as the discriminator.
This all compiles down to code that pattern matches on either the explicit tag member, or on the runtime type, and after the pattern match you basically have a normal type to work with. Hence why they are lumping it all together.
Seems more confusing than useful. Wish they’d stop adding onto this ever expanding language.
It’s like these people get bored of plain old functions and objects, read an academic paper and go “i think I’ll add that next”.
Are you suggesting that these design decisions make it through the entire process and into the language without the feature bringing a clear advantage in its use case? What would you say are the worst two or three of these C# features approved in the last decade?
Let’s assume for the sake of argument that you are correct though. The Roslyn compiler diagnostics are second to none, and pretty much any of these features will have corresponding analyzers to help remove some of that confusion, with documentation links being automatically provided if used incorrectly.
These guys aren’t writing feature proposals the way you write comments.
You’re comparing the effort of a mainstream language design proposal to a pseudonymous internet comment, wow, just wow.
Do you truly know real software developers using any these new features? I must not be working anywhere cool because I’m always having to explain what they mean in code reviews.
Imagine writing a full C# compiler in 2024, imagine if one possibly could with all these different features in this big big language.
> Are you suggesting that these design decisions make it through the entire process and into the language without the feature bringing a clear advantage in its use case?
I’m suggesting they don’t end up being adopted by enough people to be convincing. To me that leads to the shared problem with cpp, feature bloat. Multiple ways of achieving the same thing.
Since you asked, these are the three off the top of my head.
1. Init keyword is strange, why specify an accessor that only seems to apply during initialization? We already have read only for constructors. I always felt initializing objects with brackets (whatever they hell they call it) was something meant for more casual code where assignment isn’t enforced or restricted.
2. Switch expressions are ridiculous. They can get hard to read, alienating non C# programmers who come from C styled backgrounds, part of what made this language successful to begin with. They seem more like yet another syntax sugar we have to learn. And to your Roselyn comment, a language shouldn’t be dependent on Roselyns analysis to actually be usable to the general public. That is not what I’d call a cross platform language, that’s a monopolistic one where Windows/Visual Studio is the only place a not .net fanatic such as yourself can easily get work done.
3. Nullable Reference Types further over complicates what used to be a simple system of reference and value types. On top of the already head scratching nullable value types which made people question why they initially moved away from javas only reference type concept to begin with.
Slightly off topic but we have at least 3 ways to define record types: tuples, structs, and now records. I actually do like record types but unfortunately now existing code bases are polluted with the former. The point I’m trying to make in this last statement is I feel they aren’t careful enough with their proposals. They got it right with records, but look what they brought us along the way.
> Do you truly know real software developers using any these new features? I must not be working anywhere cool because I’m always having to explain what they mean in code reviews.
If you mean 9-5 devs, I am not even afforded the luxury of working with C# at all! Haven’t been since before .net core. I do ruby and devops. That being said, I have a side project with dozens of real users, closing in on double digit “market” share. I’ve needed to do some serious performance optimizations (it is a fork). The ValueType flexibility makes it easier to do these improvements.
Init applies to properties, readonly to fields (and methods in structs, or valuetype parameters).
The switch expression is something I’m also not sure about yet, but makes for less clutter in the editor. I think it’s part of a general strategy of providing the language with more compact syntax options. It reminds me of the pattern matching in F#. Did the language need those? Not really, but my biggest annoyance with older C# was the verbose syntax, and it factored into my perception at the time that it was a dinosaur language.
Roslyn is open source, cross-platform, written in C#, and can be forked. The analyzers can be linked as dependencies to any source project. I don’t understand the VS/Windows connection. They are just basically hooked methods that run during compilation steps and can emit compiler warnings, errors, suggestions, or automatically fix code. I think you are shooting yourself in the foot if you throw that feature out on pride.
Nullable reference types are optional on the file or project level and function more as type assertions, and don’t represent separate classes. I understand the frustration with it though. I think the language needed this in order to be able to statically analyze the expressions for nullability instead of relying on runtime checks. Those runtime checks are notoriously unreliable as a safety net because you have to remember to use it, and make a decision on using it. They made a tough call but I think it was the right one.
Structs are not records and are in fact mutable by default! It can be converted to a ref and then mutated, without unsafe code. The readonly modifier prevents that. I haven’t studied the nuances of readonly structs vs record structs yet. It’s considered a bad practice to use mutable structs (and undermines compiler optimization) but if you’ve ever had to refactor a class to a struct, with hundreds of usages, having the mutability can make the task much easier to do incrementally.
I think they are careful, but the decisions are very difficult and sometimes it’s a loss in either direction. C# prefers to change with the times but remain backwards-compatible, but I don’t envy the jobs of the language committee.