136 points · by benaadams · 5y ago · 184 comments
The benefit of target-typed expressions IMO is that it changes property syntax from:
public List<Foo> Foos = new List<Foo>();
to simply:
public List<Foo> Foos = new();
It may seem subtle, but if you write C# you see this pattern constantly.
Honestly, these are the features in C#9 I'm least excited about. I'm much more excited about record types, init-only setters, not to mention the improved pattern-matching and type inference (no more casting nulls inside of ternary operators!).
Immutability in C# has classically been pretty cumbersome. I work on a payroll platform where we've managed to work around a lot of that, but we're excited to introduce record types and init-only setters in particular to help with some of the maintenance pain-points surrounding the elimination of side-effects from things like pay calculations.
I am mostly excited about the sort-of option type getting rid of nulls option.
Yeah it seems like kind of a weird thing? “Here’s marginally less boilerplate once, if someone is going to learn to use the language, they may as well learn how it actually works instead of hiding stuff that they’ll soon see anyways...
It have always been a clear benefit of say Python that you can provide a two-line code snippet which can actually run.
It is also step in the continuing process of removing boilerplate. C# started out like Java, but have over time removed boilerplate where possible. "public static void Main()" is also just boilerplate.
I agree it won't matter for larger real-world program.
After all, why optimise the language for "Hello world" ? How important is that case? language designers rightly decided that supporting large programs was more important.
In the code that your team has been working on for years, you'll be glad of all of those "overhead" things, that help you manage complexity and decompose the program.
But yeah, show it to a c# newbie who is used to e.g. Python where "Hello world" is literally a one-liner and they might think "what a crapsack language, there's like 6 lines of overhead per 1 line of code, argh this is as bad as Java" - I've seen pretty much this reaction. Is it justified? From my POV, not at all. But I have seen that happen.
Top-level statements (i.e. compiler-generated boilerplate instead of Visual Studio-generated boilerplate) does seem like an "on-ramp" feature that would be discarded as the program grows past a few lines though.
Good for beginners, good for removing the overhead of "trying just one quick thing real quick"
Outside of a project that deliberately has multiple entry points so that you can compile different executables from the same code base, or code where Main is, directly or indirectly, recursive, there's no additional utility from an explicit Main(), so i don't see why implicit wouldn't win for the normal case.
public class MyClass {
private readonly MyDependency _myDependency = new();
public void MyMethodThatDoesWork() {
MyVariable variable = new();
}
}
As opposed to the (now old, IMO) var syntax/Java-like syntax mixture: public class MyClass {
private readonly MyDependency _myDependency = new MyDependency();
public void MyMethodThatDoesWork() {
var variable = new MyVariable();
}
}
Edited for HN formatting. // old:
var x = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("a", 1),
new KeyValuePair<string, int>("b", 2)
};
// new
var x = new List<KeyValuePair<string, int>>
{
new("a", 1),
new("b", 2)
}; // ListExtensions.cs
internal static class
ListExtensions
{
public static void Add(this List<KeyValuePair<string, int>> list, string key, int value)
{
list.Add(new KeyValuePair<string, int>(key, value));
}
}
// new w/extension method
var x = new List<KeyValuePair<string, int>>
{
{"a", 1},
{"b", 2},
};Sure, in your own IDE, and reading the code you just wrote, no problem. But when doing code reviews and jumping all over, I want to see the type right there. Nothing more frustrating than reviewing a PR with var's all over. This isn't even up for debate anymore... No more var!
It is frustrating to still see var as the recommended way by Microsoft... You can even put in a rule to format the document and add explicit types as well on save. So complicated type signatures for linq aren't a problem!
Anyone who names their variables properly should have no problem telling what kind of types are being worked with anyway. And in the rare case you absolutely need specifics, they’re just a tooltip away.
I always find these arguments against “var” somewhat absurd because those same programmers work with fields and properties and methods from other classes all the time, and none of those requires you to write the type.
For an example, if you were to access “someExternalThing.bigRedTrain”, the type of “bigRedTrain” would be written nowhere in the current class. I fail to see how using “var bigRedTrain” is any different.
MyFluffyGenericType<WowThisIsFun<MeToo>, MoreStuff> x = myVendorsStupidContract.SomeInsaneType;
vs var x = myVendorsStupidContract.SomeInsaneType;ooh you gotta try reviewing your PRs within visual studio [1] (and be sure to use VS internal diff tool as well) - var is no longer annoying with intellisense
[1] https://github.com/github/VisualStudio/blob/master/docs/usin...
If you really want to see type signatures everywhere, you should use something like Hungarian notation which embed type information in the name. And you should disallow method chaining and having methods or properties as parts of expressions.
But I would recommend just using an IDE instead.
Eric Lippert blogged about that like 12 years ago (when var just came out) interestingly there's a c#9 epilogue now at the bottom of the post.
If someone had told you that then you would have thought the world would have collapsed in the meantime.
- high performance is important - or interop with native libraries is required (because C#'s DllImport attribute makes that super simple)
Another benefit is that C# is syntactically similar to TypeScript (they were both designed by Anders Hejlsberg after all), so switching between the two languages feels easy. Java and Go are both similar to C# in terms of performance, but interfacing with native code isn't as simple with those languages, and they're also not as similar to TypeScript as C# is (especially Go, which is quite different).
Give .NET 5 on Linux a try, you'll be surprised!
For me, the work this team has been doing is the example of the positive "change" Microsoft has brought to the open source space. A stellar language with great infrastructure.
void printMessage(char *message) {
printf("Message from C#: %s", message)
}
You can call it from C# like this: MyLibrary.printMessage("Hello from C#!");
public static class MyLibrary {
[DllImport("MyLibraryName")]
public static extern void printMessage(string message);
}
C# takes care of marshalling data types, and an instance of a native object can be passed as an IntPtr. I'm currently developing web services for a new WebRTC-related product using .NET 5 on Ubuntu, and it's working well. One of the services utilizes a native C++ library and another utilizes a native Go-based library using the same approach. Java and Go are both good options, too.(But watch out for bitness)
One problem I've found for proprietary programs is that C# stored basically your whole source code in the executable. I don't just mean it's easy to disassemble... it's really retained the source code, or at least a lot of metadata. Even the original local variable names are there! I wonder if anyone has any ideas to work around this?
Needing to run my programs (which show up as .dll's) using dotnet just feels weird (and it doesn't match my intuition for 'how programs are run' in Windows cmd/etc).
I'd be fine with an .exe that's not self contained but at least I run it like a 'normal' exe. :)
Also, the whole thing is still a stateful operation revolving a .csproj file, which (again) is XML I have to create (sure, it's just one command) and manage/deal with every time. Even to compile a tiny C# file from my editor now I need to make a project for it. With a normal C# or C++ compiler I can just invoke csc.exe or cl.exe and produce the executable in one command from my editor... no intermediate state or project file management required. That's kind of what I was getting at with it being "simple". I didn't just mean the syntax, I also meant the structure of the solution.
For single-file-no-project simplicity your best bet is dotnet-script: https://github.com/filipw/dotnet-script
For native code your best bet is NativeAOT: https://github.com/dotnet/runtimelab/tree/feature/NativeAOT
I'm not aware of anything that combines the two.
As to why: it's not so much that they've made it hard as they haven't made it easy. The reason they haven't made it easy is that it's a fringe use case. The main benefits of AOT are faster startup time, smaller storage requirements, and compliance with the iOS interpreted language ban. Most people who worry about those things don't mind having a project file.
They _have_ made some changes that may partly address your concerns. Visual Studio is no longer required to build C#; you can do it purely from the command line. There is also a new project file format. It's still XML, but much simpler. The HelloWorld example[0] from NativeAOT is a good example of how simple it can get. And the command line tools include an easy way of creating basic project files[1], so you don't have to memorize what little boilerplate remains.
[0] https://github.com/dotnet/runtimelab/tree/feature/NativeAOT/...
[1] https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-ne...
https://stackoverflow.com/questions/861384/is-it-possible-to...
You basically install the .Net Core SDK and then run these commands to create your first executable:
dotnet new
dotnet build
dotnet run
And I suspect it is the same on the other platformsHere is an simple console example with more detail: https://www.zeusedit.com/phpBB3/viewtopic.php?f=5&t=8135
- Node.js services built with Serverless framework targeting AWS Lambda - Create React App front-ends - Gatsby front-ends
For the first, I have a single shared webpack config that I reuse for all my serverless services. For the front-end projects, I just followed the few steps to add TypeScript support to CRA and Gatsby.
- Lambda Authorizers for token auth (or use the built-in stuff if you can get away with it)
- Lambda w/ API Gateway for individual endpoints
- Aurora for relational dbms
It's really a nicely put together ecosystem.
I think a better justification is that fields and properties does not support type inference, so this can avoid some redundant type expressions for initializes, just like "var" can avoid redundant type expressions for local variables.
Of course it would be more elegant if fields/properties supported type inference like "var", but that is a can of worms since you can have recursive dependencies.
https://docs.microsoft.com/en-us/dotnet/core/porting/windows...
Winforms is probably a no-go on migration, but you should definitely check out Blazor if you want to develop any new business apps. We have constructed some incredibly complex business dashboards using this framework and cant imagine how some of this would even be possible if we had to move back to a front-end client framework and invent a bunch of JSON APIs.
Also, the new Blazor Desktop stuff is extremely exciting:
https://medium.com/young-coder/blazor-desktop-the-electron-f...
> The first difference is that the WebWindow container doesn’t use WebAssembly at all. Yes, you can run more or less the same Blazor application in WebWindow as you would in a web page. But when you use a web page, it’s executed by a lightweight .NET runtime that’s powered by WebAssembly. When you use it in WebWindow, it will use the cross-platform .NET runtime directly.
There is a lot of really amazing stuff coming down the roadmap, so I can easily advocate for enduring some degree of pain to get on this wagon.
Unless you are maintaining a Webforms project :(
Everything new is core or now .NET5, but I see no way to migrate our main website without essentially stopping all other development work for a long time.
WPF is probably dead though.
Self plug: A while back, I split off my own WPF MVVM framework from that larger project. It's designed for building simple touch-style interfaces, like you would see on a phone/tablet: https://tinyurl.com/upbeatui
For example, to use record syntax, you need to define this attribute:
namespace System.Runtime.CompilerServices { public class IsExternalInit : Attribute { } }
And supporting the new indexing syntax requires you to define System.Index and System.Range types, which are a bit more involved, but still pretty trivial:https://docs.microsoft.com/en-us/dotnet/api/system.index?vie... https://docs.microsoft.com/en-us/dotnet/api/system.range?vie...
But pretty much all the other new C# language features I've tried have just worked straight out of the box with .NET 4.7.2.
Obviously, it's not suggested doing that nor is entirely well supported, but it is at least allowed.
Though if you are looking to use top-level programs you probably are working in greenfields anyway that should just be .NET 5+. It's not really a feature that makes a lot of sense for existing codebases as it is more a teaching tool/"quick and dirty command line app/script" tool.
It emulates WebForms component with Blazor. Although I would just start from scratch.
For some of us the "upgrade path" is impassable.
MS really made a grave mistake by coupling the evolution of the C# language to the .NET version. This means all projects on the .NET framework is now also stuck with an obsolete language version for no good reason.
It is becoming a a lot less fun to be a C# developer because you more often will have to work with obsolete tools.
For the most part that isn't true. You can use later C# compilers with older frameworks. Some features do, unavoidably, require framework support.
But that being said, the changes in C# aren't often that radical that I feel particularly constrained by older versions.
gRPC is really fast and we have the WebForms monolith call into .NET Core services now so we can improve the back-end without dealing with so much ASPX crap.
It’s not directly coupled, but each version of C# has a minimum .NET version it can support, due to the requirements of the features in the language itself (like LInQ in the past).
And MS has been very up front about .NET framework being legacy and not getting any future upgrades for years now.
Keeping every new C# feature compatible with every obsolete .NET version obviously has a big technical cost. MS has clearly decided it would rather spend its effort to improve C# for those keeping up to date.
> It is becoming a a lot less fun to be a C# developer because you more often will have to work with obsolete tools.
On the contrary. The language and platform is better to work with than ever and I can do everything I need, on Linux, with just Emacs and the CLI.
I couldn’t be happier!
This
[1] https://devblogs.microsoft.com/dotnet/introducing-net-multi-...
-1 for target-typed expressions, it makes code unreadable, i'd rather see var used as field members
Riveting stuff happening in .Net land! Sarcasm aside, this seems like such a small, oddly-specific, once-off feature that its like...why bother? Any C# devs want to enlighten me here?
This mindset is one of the core features of .NET-land - Microsoft just goes ahead and implements anything useful. It's why we have a gigantic standard library ("framework") filled with every function under the sun and some multiple times. We didn't have to wait until C++20 to get string.Contains. Sometimes the features Microsoft implements are more useful than others but most of them are a little useful to somebody.
Most of the improvements that have been made in the last 10 years (aside from maybe async/await, but that pattern is pretty ubiquitous at this point) have served to reduce the amount of idiosyncrasies, not increase them.
In general, web programming has increased across-the-board in complexity manifold, regardless of your server-side language. Aside from that I find writing C# to be very succinct and logical these days compared to the past, even taking into account my own learning.
gcc -x c -ggdb -Wall -Wextra -Wno-main -Wno-unused-parameter -o $out $CFLAGS -include $header - $LDFLAGS <<-CRUN_EOF
#line 2 "$1"
$(tail +2 $1)
CRUN_EOF
Obviously gcc would be replaced with csc, you wouldn't need CFLAGS and you might need a temp file or something.Me, on the other hand, I want Python to become a compiled language. And to those who's going to reply with "PyPy/Cython/Nuitka" I have a question for them: -do show me a .dll from those!
#!/usr/bin/env swift
print("Hello")
And after a chmod +x, it works. Granted, anyone who I distribute this to will need a swift compiler installed, but that’s to be expected (and similar for Python.)Golang and other “compiled” languages have similar ways of making this work too.
This is the second one on the HN front page today [1]. HN tries to avoid paywalled articles, maybe we should also discourage articles that start out by deliberately hiding the content.
Person p1 = new();
Person p2 = new("Tom");
Person p3 = new() { FirstName = "Tom" }; public class SignPost {
public List<string> Messages { get; set;} = new();
private List<string> Errors = new();
}
In both of the above usages var is not allowed. Often-times instead of a simple list you have something like an IReadOnlyCollection<T> or an equally-abominable custom type that is just a pain to write out 2x for every time you add it as a dependency somewhere.It is becoming way to loose in a sense and it seems that it wants more than it should.
If you want to do functional programming, pick a fp language.
If you want to do dynamic typed programming pick a dp language.
Sure you can mix some things in, but c# is becoming way to scattered imo. And it's not pretty i think.
On the more substantive changes, it feels a little like the language designers have been looting F#.
Combined with how fast Dotnet Core is moving and how many breaking changes there are there, it does feel like things are getting very fragmented.
Stasis isn't good either; just witness the decade or so of stagnation after Java 1.6 as the Sun -> Oracle transition happened. But you can go too far in the other direction.
I now find myself writing half my data processing in LINQ and find myself thankful that I can chain together a few methods on a collection with possible transformation in a line or two rather than having to write 2 or 3 nested loops with all sorts of conditionals.
I'm taking the new things that come up in C# as they come, and even the ones I don't care for, I generally end up using to some extent.
Go with the flow, or pick another language, would be my suggestion.