12 ms·
C# Pattern Matching
- mindfulplay 7y agoSuch a beautiful, elegant language. Simple to grasp and lets the compiler handle all that legitimate complexity. Wish more language designers would respect code authors like these designers do.
- 0xdead 7y agoWhy are you being downvoted?
- moogleii 7y agoPerhaps because he's somewhat implying that other languages aren't doing this, but C# is actually kind of late to the game here.
- mumblemumble 7y agoIt's not that late to the game, considering its paradigm. How many other large object-oriented imperative languages have it? Not C++ or Objective-C or Java. Kotlin has destructuring, but not full pattern matching.
- dang 7y agoPlease don't do this here. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- trianglem 7y agoThank you for making this a productive space. You are getting paid for this right?
- dang 7y agoYes. Actually that fact is more interesting than it looks. It's all of our good fortune that it's in YC's interests to fund HN just as it is, with the moderators' primary job being to keep it interesting and hopefully keep the community happy. If HN were a startup, we would have to play the growth-hacking game. If it were the media property of some larger corporation, some manager would eventually put a monetization squeeze on it. Either of those tactics would ruin this place, whether or not they succeeded. YC doesn't need us to do such things because a happy HN is the most valuable-to-YC HN. It's basically an accident—a dual accident of how YC's business works and how things historically developed—that we ended up in that spot. It's a special position to be in, and our first responsibility is to preserve it. Hence our motto, Move slowly and preserve things.
- mumblemumble 7y agoI suspect that it's not an issue of respect so much as an issue of governance. C# remains a commercial language, wholly owned by a single corporate entity. That, I think, allows its maintainers some luxuries that community languages don't enjoy. Chief among them is a whole team of full-time language designers and implementers who can sustain a sort of deep concentration 40-ish hours a week for years on end. I'm pretty sure it's closing in on a decade that there's been talk about how to implement pattern matching into C#, and I'm absolutely sure that a lot of blood, sweat, and tears went into it. But that kind of effort is more manageable, on a personal level, if you're getting paid to do it and if most the thornier bits of the process are happening in a private-ish space and among a small group of people you know well. By contrast, with a community language where these decisions are made in public, by committee, and perhaps by a team of volunteers, it seems like things are always just a bit more strained. I'm sure some of the more famous PEPs took a huge personal toll on GvR, and there's no doubt that they caused a lot of high emotions. I see similarly troublesome patterns in Nim and Scala, where it would seem that "trying to avoid too much conflict with people who are forcefully communicating strongly held opinions over a medium like the Internet where it's difficult to modulate emotions" can be a real factor in the decision of what language features to include and how. And, in that kind of environment, it's probably particularly difficult to keep the Internet, with all its . . . Internetiness, at bay for long enough to really make sure you've got all the details dialed in right. Much easier, I imagine, to go for the punt and get the whole business over with.
- Kipters 7y agoTechnically it's owned by .NET Foundation now, but admittedly it's composed of MSFT people by a large part. Also, language design happens on GitHub, and the community is encouraged to get involved.
- oaiey 7y agoAs long as Microsoft finances the .NET/C# team, neither runtime/libraries nor the language will include anything which does not fit in their strategies/vision. The .NET Foundation will not change anything here. And that is good. The .NET Foundation ensures that the product is legally usable on Linux/Macs/other non Windows platforms and additionally helps the ecosystem. F# for example is set loose of these constraints.
- ryuukk_ 7y agowhy do people lie? C# is bloated and ugly, they need 3 languages to write UIs Dart/Swift/Kotlin are much better, no need extra languages, no wonder why they do better at attracting developpers
- S_A_P 7y agoResharper has proven to be a great way for me to start learning and integrating new language features. I code in my original style and resharper suggests changes based on new features like pattern matching. At first I didnt see the benefit, but this is a hugely powerful feature once you start to wrap your mind around it.
- keithnz 7y agoas an aside, if you got Rider as part of your resharper subscription, try it out, it is basically a drop in replacement for visual studio but faster and with many many little quality of life improvements you never knew you needed :)
- bob1029 7y agoThe spell checker is probably the single greatest feature in Rider. It works really well on composite type names. E.g. 'CustomerPreferences' would not get a squiggle under it for spelling, but 'CusomerPreferences' would. Performance is arguably better in most circumstances, but it doesn't support some of the bleeding edge .NET Core functionality as well as VS2019 does.
- keithnz 7y agoIt also doesn't support some dried up crusty .NET functionality like webforms either (it compiles it fine, but doesn't have the code generation tools that VS has )
- emodendroket 7y agoEvery release has more and more stuff though. Like they have added Windows Forms pretty recently. Right now SSDT and some ancient Linq2Sql stuff is the only thing I still find myself needing VS for.
- SigmundA 7y agoResharper spell checks in VS for me too.
- zwieback 7y agoIs type-sensitive code totally acceptable now? I do use it at times but generally try to avoid it.
- jdmichal 7y agoIt should be avoided, but there are legitimate use-cases. Deserialization, for example, might yield a few different types. Especially if you don't control the endpoint and the data back is a mess. When it is used, it's very nice to have help from the language. I much prefer that to some kind of purist, "they shouldn't do that so we won't help". I certainly miss having type guards when I work in Java.
- AndrewDucker 7y agoC# as standard uses camelCase for internal variables and UpperCamelCase for public variables, properties and methods. https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions https://docs.microsoft.com/en-us/dotnet/standard/design-guid...
- moron4hire 7y agoThat's not what he meant. It's not the casing of the names, it's the switching on specific types, rather than building interfaces and using generic programming.
- AndrewDucker 7y agoAh, thank you. That's what I get for commenting when tired!
- moron4hire 7y agoI'd say this is probably a bad example of usage for the feature. I use pattern matching in a few places in my own code-base, and it's almost always on interfaces that have a large set of extension methods applied. It's kind of like an entity-component architecture, except the components are added at compile-time, rather than run-time. Unfortunately, real-life use scenarios are verbose and involved and require a lot of background context that detracts from just demonstrating the syntax. This is just demonstrating the syntax. Standard patterns of software design still apply.
- rkagerer 7y agoHere's an example of the new syntactic sugar: public static double ComputeArea(object shape) { switch (shape) { case Square s: return s.Side * s.Side; case Circle c: return c.Radius * c.Radius * Math.PI; case Rectangle r: return r.Height * r.Length; default: throw new ArgumentException( message: "shape is not recognized", paramName: nameof(shape)); } } The when clause can be used to deal with special cases (e.g. to avoid division by 0 when a dimension is 0).
- aar0nsa3nz 7y agoWith C# 8 you can also write it as: public static double ComputeArea(object shape) => shape switch { Square s => s.Side * s.Side, Circle c => c.Radius * c.Radius * Math.PI, Rectangle r => r.Height * r.Length _ => throw new ArgumentException( message: "shape is not recognized", paramName: nameof(shape)) };
- derision 7y agopublic static double ComputeArea(object shape) => shape switch { Square s => s.Side * s.Side, Circle c => c.Radius * c.Radius * Math.PI, Rectangle r => r.Height * r.Length, _ => throw new ArgumentException( message: "shape is not recognized", paramName: nameof(shape)); }
- aar0nsa3nz 7y agoSorry, I couldn't figure out how to write a code block.
- derision 7y agoTwo spaces in front of each line
- moron4hire 7y ago
- throwawa66 7y agoPattern matching is so much better in F#. C# gets more and bloated to the point of paralysis. It's not yet there but I;m sure it will at some point.
- czechdeveloper 7y agoEvery single feature C# got in past years increased my productivity. I understand that it may cause issues to new learners, but overall, what of them do you consider bloat?
- throwawa66 7y agoWait till you get to work in some complex code bases and you'll understand why jamming all kinds of idioms into one language can become a disaster. It's a tool after all, if you know how to use it properly you don't paint yourself into a corner. However, too much flexibility can lead to many problems in larger teams. Good luck!
- moron4hire 7y agoI don't know, what's easier to understand? Sorting a list with an IComparer instance that you have to implement in a concrete data type somewhere, or just tossing it a lambda expression? Just because it's new syntax doesn't mean it's automatically more difficult to understand the language.
- throwawa66 7y agoI got nothing against functional programming, I embrace it. However, im stating again, shoving everything under one umbrella is bound to create a complex monster. Functional programming is actually easier to understand in F# rather than C#, the idioms do translate but clunkily. Do yourseves a favor and spend some time outside C# and you’ll come back illuminated. Not saying C# is bad, thats what you all seem to understand though. Good luck to you all
- 7y ago
- kag0 7y agoI wrote up how I'd do this in scala, just to compare and contrast val shape: Option[Shape] = ??? shape.map { case Square(0) | Circle(0) => 0 case Triangle(b, h) if b == 0 || h == 0 => 0 case Rectangle(l, h) if l == 0 || h == 0 => 0 case Square(side) => side * side case Circle(radius) => radius * radius * math.Pi case Triangle(base, height) => base * height / 2 case Rectangle(length, height) => length * height } what I noticed * scala doesn't have a way for cases to fall through, so the first cases have to each declare that the result is 0. it would be cool if we could use something in place of '=>' to make the case fall through. * C# doesn't have structural matching, so the 'when' keyword is used more often. * scala's pattern matching is exhaustive so if we assume the shapes are in a sealed type hierarchy then we don't need a default case. * it's idiomatic to use 'Option' instead of null in scala, but there are lots of libraries in c# that offer option monads, so it's more a point of what's idiomatic than what's possible.
- jolux 7y agoC# 8 also has nullable reference types, i.e. comprehensive nullability analysis, which is comparable though not identical to an option type. I really wish for exhaustive pattern matching and ADTs in C#, though.
- alkonaut 7y agoIt always feels a bit half baked when the class library isn’t designed with it though. It would be as if generics were added but not System.Collections.Generic. So while I long thought it would be the perfect addition to C#, I’m not so enthusiastic any more. It would be great (F# is!) but not as good as it would be in a language and platform where it was there all along. In F# this is already an issue when you want to use Option/Result but as soon as you do anything with the BCL you need to handle exceptions instead, and convert to/from error cases of ADTs.
- DaiPlusPlus 7y agoI’m surprised there isn’t an F# feature that automatically wraps a call with a try/catch wrapper that returns an Option<T,TException> - something like that could be done in a library, right?
- jesseryoung 7y agoI've always seen switch statements as an anti-pattern in C#. These examples however, do demonstrate neat time saving techniques. Does anybody have examples of real-world use cases that take advantage of this that couldn't (or shouldn't) be solved in a more OO way (Visitor, Strategy, Template Method, etc)
- sixothree 7y agoI try to use switches only for enums or things with a 1 to 1 simple mapping. Enums to strings for example. Although even there my preference is to use an attribute on the enum.
- rswail 7y agoExcept that enumerations are not just "strings as magic numbers". Rust's enumerations (and others) enforce that all the enumerations are dealt with in the match (a superclass of switch, mixing metaphors).
- JamesBarney 7y agoWhy are switches an anti-pattern? Switching a simple switch with a strategy pattern can make code far more complex and hard to understand. Switches are simple to code, simple to read, and easy to change.
- flukus 7y ago>Why are switches an anti-pattern? Because the gods of OO decreed as such and now the logic must be distributed across a dozen classes/files. Notice the language "that couldn't (or shouldn't) be solved in a more OO way", their goal is to create OO code, not simple to read and easy to change code.
- tigershark 7y agoBecause it’s a switch statement, not an expression and a lot of people tend to use it for doing stuff more complex than a single line. Being it a statement there is nothing that forces you to return from each case and you may forget to use the break keyword mistakenly executing also the next case.
- macca321 7y agoApologies, but here's the obligatory link to my OneOf exhaustive type matching library: https://github.com/mcintyre321/OneOf https://github.com/mcintyre321/OneOf
- throwawayy8292 7y agoHey I wanted to thank you! I stumbled across your repo a few years ago, when I was looking at more powerful ways to use the C# type system. I ended up pulling a heavily inspired version of your code into a utility library I made (for a zero dependency package). https://github.com/Matthew-Dove/ContainerExpressions#eithert https://github.com/Matthew-Dove/ContainerExpressions#eithert Once again - thanks for your contribution to my learning!
- jodrellblank 7y agoDid you just dox your own throwaway?
- throwawayy8292 7y agoYep, just got excited when I saw a familiar name I guess. Nothing too egregious on this account's history anyway.
- deleted 7y ago[deleted]
- platz 7y agoI built something simliar https://github.com/jonschoning/Unions/tree/master/Unions https://github.com/jonschoning/Unions/tree/master/Unions I went with `object` internally instead of subclasses. One thing that I like about my lib is that is serializes to json pretty well, and i added some more special-case variants such as accumulative errors (AccResult) and some applicative lifting operations.
- totalperspectiv 7y agoAt this point I would not be sad if I was forced to use C# for some reason.
- bob1029 7y agoYou should try it out sometime, regardless of coercion. There isn't much of a barrier to entry anymore. Even installing VS2019 is a pleasant experience now. I have yet to meet a developer who gave C# a legitimate try and then decided it was entirely not for them. That said, I only personally know developers who are working in the realm of B2B application development, so perhaps there are other incompatible use cases that I am blind to from my current perspective.
- DaiPlusPlus 7y agoData science, vision, etc - this is where Python reigns supreme and using C# is really going against the rest of the industry. Using OpenCV from .NET is painful, but from Python it feels native.
- totalperspectiv 7y agoYeah, this is basically the boat I'm in. Python dominates. You either write it in Python, or maybe get away with writing it in something else and then wrapping it in Python. I don't mind Python, but now that I've gotten a taste of ADT's and non-nullable types, writing Python feels like a kludge.
- DaiPlusPlus 7y agoPython (the language) feels more like a less-capable version of JavaScript now - with all of the disadvantages of lacking AOT type-safety (I know static type-checks are now available with 3.6 - but remember that most of the world is still using Python2...).
- heydabop 7y ago> Even installing VS2019 is a pleasant experience now. Even more pleasant (imo) is installing VS Code and .NET Core SDK.
- The_rationalist 7y agoFrom PHP 8 union types to C# pattern matching, I find it beautiful how languages tends to have more and more similar feature sets.It's like we're reaching a consensus on which language constructs are beneficial.
- qwerty456127 7y agoCool. I bloody wish Python is going to introduce this (and immutable (single-assign) variables) in near future.
- bilekas 7y agoI'm super embarrassed as a dotNet developer, at times 'engineer', that I don't know this.. I can't list how many time's I've ran into this kind of issue when trying to explain to a peer/intern.. (Only know I probably messed up a bit now) And HN links like this just remind me that I would love to take a 'bus mans holiday' just to catch up on the framework. This is a huge plus to the benefits of sending employees and me (please send me) to those release conferences. 'New dotNet Core coming ?' : I want to be there, but I have to live in Europe and not able to take holidays, so the stream is saved; I'll watch it later (I rarely do). :( Whatever about patterns and higher level issues, knowing the framework is also damn key important and often overlooked as a given. Really knowing the framework, all the way down to the compile time really offers some incredible results, I have been fortunate to work with some who really knew the framework versions that we were in and it was always so much fun to put bets on how much time that team would save from ours and other teams from even just a light refactor. Most important is that developers should know the framework, not because of high time savers, but so that nobody is re-writing the wheel (intentionally did not say : 'not reinventing') I wish I had the time to always dig through the release notes of the latest framework abilities, not to mention 'Core'.. I might bring this up as a task for the team, but does anyone genuinely have good suggestions on how to drill into fellow team mates that its important to check up on framework functionality.. I really feel kinda insulting to say: 'maybe google it to see if there is a simular issue that could shine a light?' God bless HN. Edit: ReSharper is my best colleague.. I'll copy an important note from below: >Note : I am not fighting against tools, just that sometimes, me included, the tools make us not go and search why resharper is screaming: 'you're an idiot'!
- GordonS 7y agoIt's OK, C# is a living thing, don't feel bad! I'm guessing you use Visual Studio and don't have ReSharper? If so, I have 2 recommendations to make: 1. Get ReSharper! When it sees code that could benefit from language features, it will suggest it 2. Get JetBrains Rider - seriously, try it - it's an alternative IDE with all the ReSharper stuff built-in. I personally find it a better experience than Visual Studio, and it makes my laptop fans whine far less!
- 7y ago
- eyegor 7y agoHeads up for C# devs, you should switch all your code bases to use (x is null) and !(x is null) instead of ==. The is operator can't be overloaded, and always compiles to IL eq, whereas == can be overloaded in custom types. Of course it would also be nice if everything was moved to nullable reference types [0], but that's a non trivial amount of work. Note that most C#8 features can be enabled manually through the csproj files, including nullable reference types, even if you're using framework. [0] https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references https://docs.microsoft.com/en-us/dotnet/csharp/nullable-refe...
- Serow225 7y agoa number of the C# lang developers prefer (x is object) for the latter, FWIW.
- eyegor 7y agoYep, looking at the IL they are equivalent. And it definitely makes code prettier due to reduced parentheses. This is also true for generics. Doing (x != null), !(x is null), or (x is object) all become: ldloc.s ldnull cgt.un stloc.s
- earenndil 7y agowhy not add an operator so you can say (x !is null)?
- gregoryl 7y agoLargely because (x is null) is a silly workaround to an uncommon and easily avoided problem (bad operator overloading).
- pbz 7y agoThe new "something is not null" check in C#8 is "something is object/set"; for example: if (x is {})
- 7y ago
- agentultra 7y agoJava is getting tuples, PHP is getting union types, C# is getting pattern matching... someone is going to announce algebraic data types and I'll die. Nice work, C#!
- tigershark 7y agoThe proposed record implementation in C# is awful, so don’t hold your breath.
- joshsyn 7y agoI have been using F# since last year, haven't really looked back to C# since. Unfortunately although we are a small community, it does feel like being last on Microsoft priority list. Microsoft please listen to feedback of your F# users namely on fslang-suggestions and fslang-design repository. My personal wish list for F# are type classes, HKTs, macros and GADTs.
- daxfohl 7y agoI'm a bit curious about the constant need of hkts. I had a fairly manufactured answer to the following question, which would have saved a couple keystrokes with hkts, but I don't yet get why it is constantly so high on the request list. It seems like something that is cool in theory but would rarely be used in real world code. https://stackoverflow.com/q/21170493/171121 https://stackoverflow.com/q/21170493/171121
- pjmlp 7y agoMy personal wish list for F# is that it just gets the same tooling and deployment scenarios support as C#, VB.NET and C++. The language is already good enough.
- vcool07 7y agoI'm surprised at the no. of recommendations for resharper even now. I thought most of the new features of resharper was already included as part of VS2019. Any specific feature that's missing ?
- ygra 7y agoResharper still has a bunch more refactoring and navigation tools. Whether that's those that are missing and you're using them, is probably up to each person themselves. The single feature I found missing all the time was smart completion which suggested matching locals/properties based on the expected type of arguments or missing expressions during typing. Everything else I tend to use, navigating to files, types, members, basic refactoring (most-used are extract local and extract method anyway) are all there and wouldn't need Resharper.
- tlwest 7y agoA new construct to save a line of code? Whatever happened to "every proposed language feature starts at -100 points, and must must become positive to even possibly be considered."? Given that probably 90% of code is written by C or D class programmers, every new feature adds cognitive load that makes it less likely that the median programmer (who almost certainly works offshore and who likely doesn't have enough English skills to process the tutorials) will write bug-free code. Once upon a time MS understood that highly educated university graduates are only a small percentage of the programmer market and kept that in mind. Looking at the new language changes, that's been forgotten in order to please the programming elite. Spare a thought for the poor souls who curse every time Microsoft adds a new blade to the Swiss Army knife of C# because they know they'll be the ones mopping up the blood of the countless programmers who've cut themselves on the new feature.
- deleted 7y ago[deleted]
- goto11 7y agoI feel for you! But people misusing language features is not really the fault of the language per se, it is more a failure of process, culture, tests and code reviews. I don't believe dumbing down a language leads to fewer bugs, it will just lead to more verbose bugs.
- eyegor 7y agoDoes anyone know of or can think of a use for (x is var y)? I'm assuming there must be, but I just can't figure it out.
- brianpgordon 7y agoI don't think anyone has mentioned yet that this exact feature (with the "is" keyword) is actually coming to Java as a preview feature in Java 14- https://openjdk.java.net/jeps/305 https://openjdk.java.net/jeps/305
- martijn_himself 7y agoThis is neat, but also super confusing. Is the ability to build class hierarchies not the ultimate reason to use C#, an Object-Oriented language? Which one of the two is idiomatic? Great, now we have code littered with methods that take objects as parameters, so we have no clue what to actually pass to the method? C# is a fantastic language but I feel increasingly lost with the barrage of new features added to it.
- 1propionyl 7y agoClass hierarchies are not a desirable feature of object-oriented languages, they're an unfortunate side effect of their historical development. (For example, early versions of Java did not actually have the interface keyword at all.) There are several very good reasons that the inherited wisdom about OOP includes such phrases as "prefer composition and delegation over inheritance". There are some cases where class hierarchies are actually good, but they're far rarer than most would suspect. The Liskov Substitution Principle is less of a guide as to how to use inheritance as much as it is a guide as to when you should not be using inheritance at all. And to address your point: the only time objects with class hierarchy and subclases should be accepted as arguments to methods is precisely when the LSP holds. Otherwise, you're gonna have a bad time.
- martijn_himself 7y agoThese are all valid points and it shows my lack of understanding (same with the other comments), even though I use C# on a semi-regular basis I have a lot to learn! I don't envy any newcomers to the language though, there is so much to take in.
- 1propionyl 7y agoMy general advice to anyone working with C# is the same advice given by the authors of Smalltalk to developers. 1) Always prefer composition and delegation to inheritance. 2) Always prefer interface inheritance to implementation inheritance even if in the short term it results in code clones. 3) If you intend to have multiple subclasses that adhere to the Liskov Substitution Principle, it is always better to have IFoo and X implements IFoo, Y implements IFoo... than it is to have abstract class Foo where X, Y extend Foo. You can still do that, behind the scenes, but your public interface should whenever possible be nearly entirely interfaces and concrete classes. 4) Inheriting the body/behavior of methods is seductive but ultimately only a poor excuse for not delegating that will create maintenance headaches down the line.
- SideburnsOfDoom 7y agoC# 8 also has "switch expressions" (1) meaning that all those "return" keywords fall away so this is valid (although useless) c# 8: public static bool Invert(bool value) => value switch { true => false, false => true }; I worry though that the "switch" syntax is becoming a big complex monster, and can be used to make utterly unreadable code, rather than simplifying as promised. We'll probably see both in practice. It might have been nicer if they could have used a new keyword e.g. "match" to carry the new syntax, rather than overloading "switch", but that would not be backwards compatible with C# 1-7, as "match" was not a reserved word. (2) Hopefully switch the syntax that supports these various cases doesn't get too tricky. 1) https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csh... 2) https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...