125 points · by plurby · 9y ago · 98 comments
Asynchronous Streams
Now you can "yield" Task<T> (~ Future<T> in Dart) and construct LINQ chains in an asynchronous fashion.
I hope it streamlines reactive programming greatly.[1] Dart - Asynchronous Programming: Streams https://www.dartlang.org/tutorials/language/streams
[2] .NET Futures: Asynchronous Streams https://www.infoq.com/news/2017/05/async-streams
Besides that, the feature I want most in C# is enum exhaustion checking. So I can write:
enum Color { red, green, blue };
public static string SuperheroFromColor(Color c)
{
if (c == Color.red)
{
return "Superman";
}
else if (c == Color.green)
{
return "Green Lantern";
}
else if (c == Color.blue)
{
return "Spiderman";
}
}
and not get a compiler error (that not all code paths return a value). But if I added "yellow" as an enum option, then I would get a compiler error. I realize that Color can be cast from an out-of-range int, so it's a little complicated. I'm willing to put something extra after the last else: unreachable return null;
or use a special switch statement. I just want something so the compiler checks that I have accounted for all normal enum values.Is anyone talking about such a feature, or where would I request it? Can I write it myself as a Roslyn extension?
type Color = Red | Green | Blue
let superheroFromColor c =
match c with
| Red -> "Superman"
| Green -> "Green Lantern"
| Blue -> "Spiderman"
However, if you add Yellow as a new case to the Color discriminated union without adding a corresponding match pattern everywhere you match a Color value, you get a compiler warning: type Color = Red | Green | Blue | Yellow
...
match c with
----------^
warning FS0025: Incomplete pattern matches on this expression. For example, the value 'Yellow' may indicate a case not covered by the pattern(s).
Aside: notice how terse and readable the code is compared to the C# equivalent; F# tends to have a high signal-to-noise ratio.It doesn't do that for me on VS2012 or in .NET Fiddle: https://dotnetfiddle.net/f4NSvf
Plus what you're asking for is a maintenance nightmare; since changing the type (Color) in one part of the code can break method definitions in another part of the code (inc. other assemblies).
I'd hope they would never support what you're asking for.
It does sometimes mean that when you update some code, you have to update a bunch of other things. But it's rarely spurious. Usually those other things are broken by failing to consider the new possibility.
In the long term, it's a maintenance win.
Better to ask for a C# union type and matching syntax.
Is there a way to write that SuperheroFromColor function so that I will get a compiler error (or warning) if another option is added to the enum? (Imagine that function is far away from the Color definition so it's not visually obvious.)
When I create an enum with three possible values, I reason about it as having only three possible values. As long as I never cast from an int, that should be true, right? So I don't want to consider the "and others" possibility. It's hard to even think about what to do in that situation, since it shouldn't happen.
I said that I'm willing to put some keyword before or after the if statement to tell the compiler to make sure I'm handling all valid enum values. So it can only give me these errors (or warnings) when I ask for them.
I think pattern matching in Haskell will make sure you handle all possible cases and give you a compiler error if you don't. I'm asking for a "poor-man's version of pattern matching for enums" in C#.
Adding a new member to the Color enum should break code that isn't written to handle it: which is any code written before Color.yellow was introduced.
* Scaring potential customers away with said contracts and suing customers
* Google walking out on Java going with Kotlin instead....boom billions of users moving to a different language. Still on the JVM though....but that's not a hard requirement.
If anything, Java (the language) is probably improving at a faster rate now than ever before but much of the damage is already done.
Has been cool the last few years as well.
And it runs in many systems that .NET still doesn't, so adding features without doing a Python 3 is very important.
The `!`'s are always code smells. I hope I can turn them into warnings or build errors.
// Unholy mix of Swift and C# syntax ahead!
if var unwrappedString = wrappedString && unwrappedString != "" {
unwrappedString.Length();
}
Where the `if var unwrappedString = wrappedString` part would unwrap the var and return a `bool` at the same time which is `true` if it wasn't `nil`.Swift's nil-checking / unwrapping syntax is really short and with some clever usage of `map` or `flatMap` you can still have one-liners albeit a bit more verbose - but much more secure.
Example of using map:
let myTitle = myObject?.title.map { "Item \($0)" } ?? "No title"
This code can't even theoretically crash anymore and doesn't force unwrapping with `!` as a traditional approach would do: let myTitle = myObject?.title != nil ? "Item \(myObject!.title!)" : "No title"The problem is that lambdas aren't free. For something as simple as a null check, the overhead of a lambda is excessive. Zero-cost lambdas are possible, but require a new type of lambda that cannot escape the enclosing scope, all reflected in the type system.
* Nullable Reference Types This makes it so much easier to reason about references. I always found it strange that C# had nullability on value types, but not on reference types.
* Default Interface Implementations Inherit an interface, and get an implementation "for free". This makes for a very powerful way to define interfaces and default implementations.
* Extension Everything As noted in the video/text, the current syntax feels a bit weird -- having to use a static class.
[1]: Not saying these are exclusive to Swift, or Swift was the first to implement them.
As a heavy TypeScript user myself, it was easy to see the parallels between the designs: question mark nullability, the compiler-enforced nullability checks rather than runtime-enforced, "dammit operator" to override the compiler. All shared between TypeScript and C#.
I love this feature in TypeScript; it's help me find numerous bugs and helps me reason about my code. I'm looking forward to using it in C#.
Anders and I meet every week to compare notes, and I make sure to get his input on major new features in C#.
At least given his latest interviews on Channel 9 and BUILD sessions.
Version 1.0 of C# was the same as Java: Nullable reference types and non-nullable value types. Nullable value types didn't come until version 2.0 but at that point ir was too late to make reference typed non-nullable.
I'm glad they're actually putting the effort to fix this issue now. It's a huge task given the amount of legacy code out there.
However, that's a new way to check for null in the language, where what we need is to recognize the ways people are already checking for null in billions of lines of code. Therefore, the priority is to do a good flow analysis that will just understand when a nullable variable can be assumed to not be null (e.g. after a check, a non-null assignment, etc.), and then let you dereference without challenge.
Another Swift feature that I think leads to very poor readability is trailing closures.
So basically multiple inheritance?
Personally as a developer I really like having the choice whether to buffer in one place in my system (using a persistent queue f.i.) and have the rest of the system cooperate in tandem without running out of memory f.i. Or to choose to ignore elements when stuff is just going to fast. Etc. I feel more in control of the behaviour under load of my system.
I guess Lightbend was onto something when they took the old EAI notion of backpressure (as f.i. described in Gregor Hohpes book) and implemented it in stream processing and started an interoperability standard around it.
What they talk about here, with explicit nullable reference types is so close but stumbles at the last hurdle. Having some kind of opt in on the compiler that makes regular references non-nullable is great for new projects (and arguably the best thing for the language itself), but leaves all legacy code out in the dark. You can't switch on a compiler option like this on any big existing project without massive effort. (And massive effort means management approval and planning and justification)
They got the case by case opt on the wrong part of the feature. It's really the non-nullability of a reference that's most important to be able to be opted in to on a case by case basis. (And case by case opt in means low effort, so it doesn't need big up front approval or planning, you just get on and write better code with fewer bugs.)
What's really needed is something like this
String! s = null;
Where the ! makes the s reference non-nullable, so any attempt to assign null (or anything that could be null) to it is a compiler error.And it's so disappointing because he comes so so close to that at the end with his talk of s!. as a way to say that you know something is not null, but it just doesnt quite get the benefit right.
It's non-nullability of reference types that should be the central feature here.
I'm just really hoping that these guys know what they are doing, and it's just he couldn't explain the subtleties in a short video, and this is going to turn out working the right way in the end.
The feature only really started to gel when we realized the important feature was nullable reference types. The thing is, in most code, most things aren't actually supposed to be null. So we want non-null to be the default.
When you start marking the things that should be null as such, you'll be protected from dereferencing those without a check. That's what actually prevents you from getting null-reference exceptions!
And once you've marked them all (usually a fraction of your type annotations), null really doesn't have a place in the remaining spots, and you can turn on the non-null check to eradicate those.
This leaves you with the smallest number of places to update your existing code, and leaves new code the cleanest.
If it's just a compiler warning (and you don't treat warnings as errors) then can't you leave it on and do the work gradually? Or turn it on for a day, do some work, and turn it off again? You have to eat the elephant somehow.
Also, even if you make the non-nullability opt-in on a case-by-case basis, don't you still need a compiler switch to turn on occasionally and see what remains to be done?
Yes, this sucks for existing code. I suspect that we'll get some kind of file-level switch, so that you can port things one class at a time - there's no reason why that switch has to have the same value for all files in the project.
Yeah, or a file level switch would do, that would be fine. As long as there is some way of transitioning a project little bit at a time.
I hope we get one of those options
Coming from C++ it seemed like C# interfaces (and Java at the time) felt like a punishment. Now I'm sort of used to them.
Lambdas vs nested functions is an example that comes to mind (during the Microsoft Build conference presentation of the feature, the presenters jokingly admitted that nested functions arose from Javascript's popularity).
I felt like the value-add of nested functions over lambdas, versus the growth of language complexity, was not great enough to add nested functions as a language feature. (Of course, that's just my opinion.)
But the bigger question is, what's the threshold where software and languages go from being "feature rich" to "bloated"? And are there cases in the past where the corporate stewards of a language have found that sweet spot?
C# has been a great language. I use it every day.
But it feels like the inevitable end game for this language, and maybe every language with corporate stewardship, is that the pressure to release new versions to "keep up with what's hot" eventually ends in the death of the technology by a thousands cuts (where, in this case, by cuts we mean unnecessary features).
(To be fair, the language stewards so far have been batting 900. They've generally done a great job at this so far.)
using System.Linq;
foo.Select(x => bar);
from itertools import *
imap(foo, lambda x: bar)And I discuss some ways that could be integrated with the extension everything proposal here: https://github.com/dotnet/csharplang/issues/164
The problem with both is that there's a new notion of "shape" or "concept" that's different from interfaces. It would be nice to just use interfaces for this (which is what I hint at in the video), but that comes with its own downsides and limitations.
Really? I'm not an expert but everything I've read until this implies the opposite. Besides, C# already has implicit conversions, and they're different from type classes in that they convert, not extend. Once an int is implicitly converted to a double, it's always a double from within the function that converted it, not just "representing" a double. So strictly less powerful than polymorphism. My understanding that type classes were the way out of that, and traits were Scala's equivalent. Is that not correct?
trait Show[T] { def show(v : T): String }
implicit object ShowInt extends Show[Int] {
def show(i: Int) = i.toString
}
def showLine[T](v : T)(implicit show: Show[T]): Unit = {
println(show.show(v))
}Assume you're thinking about C#'s extension methods, which in Scala are achieved via implicit classes.