12 ms·
What's New in C# 14: Null-Conditional Assignments
- deleted 1y ago[deleted]
- wslh 1y agoIsn't this more confusing? Because it skip the code if the value is null and I don't think it is normal to follow the flow assuming nothing has happened.
- cjbgkagh 1y agoIt’s for the use case where they’d skip it anyway so that would be intended behavior.
- accrual 1y ago> I don't think it is normal to follow the flow assuming nothing has happened. I think it is for situations where the programmer wants to check a child property but the parent object may be null. If the parent is expected to be null sometimes, the syntax lets the programmer express "try to get this value, but if we can't then move on" without the boilerplate of explicitly checking null (which may be a better pattern in some cases). It's sort of like saying: - Get the value if you can, else move on. We know it might not be there and it's not a big deal. v.s. - The value may not be there, explicitly check and handle it because it should not be null.
- BoiledCabbage 1y agoYour summary is almost correct but replace where you used "get" with "set".
- accrual 1y agoThanks! Yes, mistake on my part.
- electroly 1y agoThat's already the case for the null coalescing operator when it ends in a method call: the method call is skipped if the base is null. For instance, we can invoke event handlers with "myEvent?.Invoke(...);" and the call will be skipped if there are no event handlers registered, and this is the canonical way to do it.
- gus_massa 1y agoFrom the article: > If config?.Settings is null, the assignment is skipped. If the right hand expression has side effects, are they run? I guess they do, and that would make the code more predictable.
- Izikiel43 1y agoFrom the article as well: Side-Effect Prevention When a null-conditional statement assignment is evaluated, the right-hand side of the expression is not executed unless the left-hand side is defined.
- gus_massa 1y agoThanks. I missed it. I really dislike that, because it hides the control flow too much. Perhaps I'm biased by Racket, where it's easy to define something weird using macros, but you should not do unexpected weird things. For example you can define vector-set/drop that writes a value to a position of a vector, but ignores the operation when the position is outside the vector. For example (vector-set/drop v -2 (print "banana")) With a macro is possible to skip (print "banana") because -2 is clearly out of range, but if you do that everyone will hate you.
- ygra 1y agoI think in the context of C# this is not exactly unexpected since there are various operators that apply conditional execution (and evaluation) to parts of an expression. All of them start with ?, though (? :, ??, ?., ?[], ??=), so except for casts to nullable types, every question mark in an expression signals that control flow is about to happen and it's been that way in C# for quite a while.
- gus_massa 1y ago[Too late, sorry for the delay, but I had to think about it.] That ooks like a good reason. Looking at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator https://learn.microsoft.com/en-us/dotnet/csharp/language-ref... , the magic is in the LHS or the RHS, and in ??= the magic is explicitly in the connection. Here, IMHO, the problem is that the magic jumps from one side to the other. Anyway, I don't use C#.
- alkonaut 1y agoIt kind of is more confusing because I always imagined the RHS to be evaluated first in an assignment, before the target is evaluated. The motivation is that you don't want the side effects in some cases like GetNextId() but I think it's still strange. I hacven't thought deeply about it but i _think_ I'd rather keep the intuitive right-hand-first evaluation and explicitly have to use if (..) in case I have a RHS whose side effects I need to avoid when discarded.
- sieep 1y agoLooks interesting & I'm excited to try this out myself. I like the more verbose null/error handling personally in professional code, but maybe that's because im still working in framework! I'll certainly be using these in my personal projects that'll be on .NET 10
- actionfromafar 1y agoYou can use newer LangVersion in framework too.
- sieep 1y agoTrue. I'll go nag the senior to start updating that for the 100th time.
- coneonthefloor 1y agoI’d rather be explicit. If the value is null then it should be explicitly handled. I feel like this is another step in the race to add every conceivable feature to a language, for the sake of it.
- deleted 1y ago[deleted]
- xboxnolifes 1y agoThis is explicit though. The question mark operator is the developer explicitly asking for this behavior.
- deleted 1y ago[deleted]
- zulu-inuoe 1y agoI'm looking forward to being able to use this. It doesn't sound like much but those extra three lines and variable assignment is duplicated a ton of times across our codebase so it'll be a nice change
- reactordev 1y agoLove to see conciseness for the sake of readability. Honestly I thought this was already a thing until I tried it a year ago… I’m glad it’s now a thing. It’s an easy win, helps readability and helps to reduce the verbosity of some functions. Love it. Now, make the runtime faster…
- kazinator 1y agoNull conditional assignment is bunk. When you have an expression P which names a mutable place, and you execute P := X, the contract says that P now exhibits the value X, until it is assigned another value. Conditional assignment fucks this up. When P doesn't exist, X is not stored. (Worse, it may even be that the expression X is not evaluated, depending on how deep the fuckery goes.) Then when you access the same expression P, the conditional assignment becomes conditional access and you get back some default value like a nil. Store X, get back nil. That's like a hardware register, not a durable memory model. It's okay for a config.connection?.retryPolicy to come up nil when there is no config.connection. It can be that the design makes nil a valid retry policy, representing some default. Or it could be that it is not the case, but the code which uses connection? handles the nil soon afterward. But a store to config.connection?.retryPolicy not having an effect; that is dodgy. What you need for config.connection? to do when the expression is being used to calculate a mutable place to assign to is to check that config.connection is null, and in that case, instantiate a representative instance of something which is then assigned to config.connnection, such that the config.connection.retryPolicy place then exists and the assignment can proceed. This recognizable as a variation on COW (copy-on-write); having some default instance for reading, but allocating something on writing. In a virtual memory system, freshly allocated memory can appear to contain zero bytes on access due to all of its pages being mapped to a single all-zero frame that exists in the entire system. Conceptually, the hardware could do away with even that all-zero frame and just have a page table entry which says "this is a zero-filled page", so the processor then fakes out the zero values without accessing anything. When the nonexistent page is written, then it gets the backing storage. In order to instantiate settings.connection? we need to know what that has to be. If we have a static type system, it can come from that: the connection member is of some declared type of which a representative instance can be produced with all constructor parameters defaulted. Under a dynamic paradigm, the settings object can have a handler for this: a request to materialize a field of the object that is required for an assignment. If you don't want a representative config.connection to be created when config.connection?.retryPolicy is assigned, preferring instead that config.connection stays null, and the assignment is sent to the bit buckets, you have incredibly bad taste and a poor understanding of software engineering and programming language design --- and the design of your program is scatter-brained accordingly.
- rkagerer 1y agoMore concise? Yes. More readable? I'm less convinced on that one. Some of those edge cases and their effects can get pretty nuanced. I fear this will get overused exactly as the article warns, and I'm going to see bloody questions marks all over codebases. I hope in time the mental overhead to interpret exactly what they're doing will become muscle memory...
- arwhatever 1y agoWhat?.could?.possibly?.go?.wrong?.
- esafak 1y agoif (This) { if (is) { if (much) { if (better) { println("I get paid by the brace") } } } }
- muti 1y agoif (!same) { return; } if (!number) { return; } if (!of_braces) { return; } println("but easier to read")
- esafak 1y agoYes, you should definitely unnest functions and exit early. But the null-coalesced version is shorter still.
- kazinator 1y agoFalse dichotomy. The problem is that the syntax implements a solution that is likely wrong in many situations and pairs with a bad program design. Maybe when we have this: what?.could?.possibly.go?.wrong = important_value() Maybe we want code like this: if (!what) what = new typeof(what); // default-construct representative instance if (!what.could) what.could = new typeof(what.could); if (!what.could.possibly.go) what.could.possibly.go = new typeof(what.could.posssibly.go) // now assignment can take place and actually retain the stored value // since we may have allocated what, we have to be sure // we propagate it out of here. what.could.possibly.go.wrong = important_value(); and not code which throws away the value (and possibly its calculation). Why would you ever write an assignment, but not expect that it "sticks"? Assignments are pretty important. What if someone doesn't notice the question marks and proceeds to read the rest of the code thinking that the assignment always takes effect? Is that still readable?
- deleted 1y ago[deleted]
- billmcneale 1y ago> if (customer?.Profile is not null) >{ > // Null-coalescing (??) > customer.Profile.Avatar = request.Avatar ?? "./default-avatar.jpg"; >} Isn't this over engineered? Why not allow the assignment but do nothing if any of the intermediate objects is null (that's how Kotlin does it).
- LelouBil 1y agoThat's what's new in c#14, it allows you to do customer?.Profile?.Avatar = "thing" And will do nothing if the left hand side is null (not throw a null reference exception anymore)
- LelouBil 1y agoI'm working on a Unity game and I'm so annoyed I can't use all of the new fancy c# features
- drzaiusx11 1y agoSo like ruby's '&.' null safe chaining
- Dylan16807 1y agoYes but they already had it for non-assigning uses.
- dominicrose 1y agoRuby is a true OOP programming language unlike all the ones who just pretend to be. It's similar to Smalltalk in many regards. In Ruby only nil and false are falsy (and they are both objects with their respective classes) so for non-boolean types we can just use ||=. It works with undefined variables as well. This strong typing also means we can use the = operator in if statements. Compare that with PHP where the "0" string is falsy and where even the array has no class (so no methods).
- tialaramex 1y agoAt least so far, my instinct is that we should turn this off/ ensure it is never turned on, as it seems likely to be a foot gun. I couldn't imagine what a "Null-Conditional Assignment" would do, and now I see but I don't want this. Less seriously, I think there's plenty of April Fools opportunity in this space. "Null-Conditional Function Parameters" for example. Suppose we call foo(bar?, baz?) we can now decide that because bar was null, this is actually executing foo(baz) even though that's a completely unrelated overload. Hilarity ensues! Or what about "Null-Conditional Syntax". If I write ???? inside a namespace block, C# just assumes that when we need stuff which doesn't exist from this namespace it's probably just null anyway, don't stress. Instead of actual work I can just open up a file, paste in ???? and by the time anybody realises none of my new "classes" actually exist or work I've collected my salary anyway.
- bandyaboot 1y agoI’m having a hard time imagining where this is useful. If I’m trying to assign to a property, but encounter an intermediate null value in the access chain, just skipping the assignment is almost never going to be what I want to do. I’m going to want to initialize that null value.
- deleted 1y ago[deleted]
- moogly 1y agoI'm also not sure I have a lot of code where this would be useful, but adding it to the language I don't feel makes it worse in any way; in fact, it makes it more consistent since you can do conditional null reads and conditional null method invocations (w/ `?.Invoke()`), so why not writes too.
- layer8 1y ago“Why not?” is never a good-enough reason to add a new language feature. If it’s rarely used, people may misinterpret whether the RHS is evaluated or not when the LHS doesn’t exist (I don’t actually know which it is). Optional operations and missing properties often require subtle consideration of how to handle them. You don’t want to make it too easy to say “whatever”.
- moogly 1y ago> people may misinterpret whether the RHS is evaluated or not when the LHS doesn’t exist I fully expect no RHS evaluation in that case. I think the fear is misplaced; it's one of those "why can't I do that when I can do this" IMO. If you're concerned, enable the analyzer to forbid it. There are already some really overly paranoid analyzers in the full normal set that makes me wonder how masochistic one can be...
- notTooFarGone 1y agoAdding something is always gonna make things worse by default and has to be proven to be useful. Otherwise you have bloat and "yet another way of doing the one thing". I'm a fan of this notation because it's consistent but language design should not just add features because it doesn't hurt.
- vjvjvjvjghv 1y agoIt's starting to feel like C# is going down the path of C++. Tons of features that introduce subtleties and everybody has their own set of pet features they know how to use. But the code gets really hard to understand when you encounter code that uses a subset you aren't familiar with. I remember staring at C++ codebases for days trying to figure out what is going on there. There was nothing wrong with the code. I just wasn't too familiar with the particular features they were using.
- koyote 1y agoThere's a couple reasons I disagree with you on this (at the moment; as given enough time I am sure C# will also jump the shark): * The above is just applying an existing (useful) feature to a different context. So there isn't really much learning needed, it now just 'works as expected' for assignments and I'd expect most C# engineers to start using this from the get go. * As a C# and C++ developer, I am always excited to hear about new things coming in C++ that purportedly fix some old pain points. But in the last decade I'd say the vast majority of those have been implemented in awful ways that actually make the problem worse (e.g. modules, filesystem, ...). C#'s new features always seem pretty sound to me on the other hand.
- jayd16 1y agoThe difference is the language syntax choices are good. There's no "what does this const refer to" type confusion.
- vjvjvjvjghv 1y agoAgreed about the syntax choices. Much better than C++. The language is just getting a little too big for my taste.
- swoorup 1y agoA C# dev can't complain, because complexity creates job.
- moomin 1y agoAt a social level, I 100% agree with you because I’ve started to see those behaviours in the community. But considered technically, C++ is on a whole different level from C#. The community seems to embrace “What does this print?” style puzzles, and figuring out when perfect forwarding or SFINAE kick in is genuinely tricky. Static abstract methods are probably the feature I see used least (so far!) and they’re not nearly as hard to understand as half of the stuff in a recent C++ standard.
- LAC-Tech 1y agoIs .NET entering its twilight years as a tech people build new things with? I just can't imagine Gen Z wanting to start a project in C#. I realise there are still .NET shops, and I still talk to people who do it daily, but ours is a field driven by fashion whether we care to admit or not - and C# just does not feel as fashionable as it once did (I'm a former C# dev, up until 2020)
- Merad 1y agoI've been using .Net for almost 20 years, professionally for half that time, and I feel like excitement and momentum in the community has only been increasing.
- BrouteMinou 1y agoSame story here. I decided lately to focus more on .net and, let's say, abandon Java. It's portable, fast, productive and well supported by a massive corp. It's not just a "language du jour", it's here to stay. There are plenty of job in dotnet where I live: old, new, startups... I am the momentum!
- recursivecaveat 1y agoIt is definitely out of fashion, most directly in comparison to Go I suppose. It seems like they tried with .NET Core, but were not able to provide an appealing and coherent enough on-ramp. The ongoing death of native windows applications not helping either certainly.
- koyote 1y agoI personally can't think of an all-rounder language that is better than C#. It's fast, has great tooling, powerful, extremely productive for working with large code bases and runs 'anywhere'. JS has lost against TS which is basically C# for web (both designed by the same person) and Python is not really something you should build large applications with (execution speed + maintenance issues). What do you believe is the current language du jour?
- 1y ago
- aldousd666 1y agoLike Ruby safe navigation operator `&` and kotlin, groovy and swift's `?`
- peterashford 1y agoI'm a Java fan so I'm contractually required to dis c#, but actually I kinda like this. It reduces boilerplate. Yes, it could be abused but this is what code review is for.
- moomin 1y agoYou’re not wrong. Every language feature that gets added there’s someone who wants to stop the clock and hold the language definition in place because “people might misuse it” or “people might not be familiar with it”. It’s not language specific, it’s everywhere.
- ffsm8 1y agoStill, enabling ?. Access on the left side of the equals (assigning) feels like a serious anti pattern to me I struggle to even see how anyone would prefer that over an explicit if before assigning. Having that on the right side (attribute reference) is great, but that was already available as far as I understood the post...
- rkomorn 1y agoAs someone who comes from a language with no ? (or equivalent) who only dabbles in C#, it actually seemed a little weird to me that this was one of the contexts where it wasn't usable. So as a casual observer, I'd say it brings more consistency. But also as a casual observer, my opinion is low-value.
- fakwandi_priv 1y agoThe point the article is trying to make is that it reduces boilerplate, wouldn't be surprised if this gets added to TS in the next year of two.
- hahn-kev 1y agoWithout it there's some silly inconsistency. For example I could call `person?.SetName(name)`, but if you wanted to refactor that into `person?.Name = name` you can't.
- tekdude 1y agoI wonder if this supports a cleaner way to throw when the target property's parent object is null? With null-coalescing assignment, you can do the following which will throw when 'x' is null: string x = null; string y = x ?? throw new ArgumentException("x is null"); It would be interesting to try something like: customer?.Name = newName ?? throw new InvalidOperationException("customer is null"); But I don't know how the language would be able to determine which potential null it was throwing for: 'customer' could be null, but so could 'newName'. I guess... maybe you could do: (customer ?? throw new InvalidOperationException("customer is null")).Name = newName ?? throw new ArgumentException("newName is null"); But the language already supports that, and it's extremely ugly...
- RomanPushkin 1y agoNice feature! (we had in Ruby for many years)
- dionian 1y agonever using nulls is liberating. this is syntactic sugar for dealing with nulls. definitely welcome though, and definitely will be abused (which cant be done when nulls are actually banished)
- alkonaut 1y agoWhen you don't, you'd likely have an Maybe<string> for a username that would be a "string?" in C#. It's the same thing (more or less). For your optional type you still need some form of pattern matching to figure out whether you have it or not. You can't banish the "absence of value" from any programming language. That wouldn't be a useful language. You can stop confusing "a string but perhaps not" as a single type "string" as C# did in the past though.
- maltalex 1y agoCute, but is this actually needed? It's one more thing to remember, one more thing to know the subtleties of, and for what? To save writing a very readable and unambiguous line of code? It feels like the C# designers have a hard time saying "no" to ideas coming their way. It's one of my biggest annoyances with this otherwise nice language. At this point, C# has over 120 keywords (incl. contextual ones) [0]. This is almost twice as much as Java (68) [1], and 5 times as much as Go (25) [2]. And for what? We're trading brevity for complexity. [0]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/ https://learn.microsoft.com/en-us/dotnet/csharp/language-ref... keywords/ [1]: https://en.wikipedia.org/wiki/List_of_Java_keywords https://en.wikipedia.org/wiki/List_of_Java_keywords [2]: https://go.dev/ref/spec#Keywords https://go.dev/ref/spec#Keywords
- buybackoff 1y ago> is this actually needed Yes, actually. I did write it multiple times naturally only to realize it was not supported yet. The pattern is very intuitive.
- ygra 1y agoI stumbled over this a few times, mostly when cleaning up older code. This basically just means that using the ?. member access no longer dictates what is possible on the right side. Property reads were fine before (returning null if a part of the chain was null), method invocations were fine (either returning null or just being a no-op if a part of the chain was null). But assignments were not, despite syntactically every ?. being basically an if statement, preventing the right side from executing if the left side is null (yes, that includes side-effects from nested expressions, like arguments to invocations). So this is not exactly a new feature, it just removes a gotcha from an old one and ensures we can use ?. in more places where it previously may have been useful, but could not be used legally due to syntax reasons.
- bob1029 1y agoNothing is stopping you from constraining the language version you want to be used in your projects: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version https://learn.microsoft.com/en-us/dotnet/csharp/language-ref... You can force it all the way down to ISO-1/2. If this is still insufficient, then I question what your goals actually are. Other people using newer versions of C# on their projects shouldn't be a concern of yours.
- DeathArrow 1y agoWhile this is nice, there are some long requested features like Discriminated Unions that got delayed a lot.
- SideburnsOfDoom 1y agoDiscriminated unions are a hard feature to put into a mature language that already has other features in a similar space - I mean enums and class hierarchies. (.e.g. if your union is "Cat or Dog", then in OO terms they have a common base class "Animal" ). How does it play with records, structs, generics, etc etc. That is why although they are much requested, none of the proposals that I have seen are simple to understand or easy to implement, and thus are proceeding slowly. I don't really see Discriminated union as being in "competition" with "a?.b = c" as that's a "quick win" extension to previous ?. and ?? syntax. It's not even close to being of the same magnitude. I would settle for a good built-in Result<T, E> type, so that people don't roll their own crappy ones, or use various opinionated but incompatible libraries.
- Metasyntactic 1y agoHi there. C# lang designer here :) Discriminated unions continue to be worked on, and you can see our latest designs here: https://github.com/dotnet/csharplang/blob/main/proposals/unions.md https://github.com/dotnet/csharplang/blob/main/proposals/uni... The space there is large and complex, and we have a large amount of resources devoted to it. There was no way that `a?.b = c` was going to change if/when unions come to the language. For unions, nothing has actually been delayed. We continue working hard on it, and we'll release it when we think it's suitable and ready for the future of the lang. The only feature that actually did get delayed was 'dictionary expressions' (one that i'm working). But that will hopefully be in C# 15 to fill out the collection-expression space.
- DeathArrow 1y agoThank you for working on it, I hope we will see it in a release soon. By delayed I mean that the committee was discussing about discriminated unions since a long time ago and it was never "the right time". You can see the discussions related to implementing discriminated unions on Github.
- vivegi 1y agoThis sounds like a shortcut, unless it isn't. I have a feeling this is going to make debugging code written just a few months ago incrementally difficult. At least the explicit if statements are easier to follow the intent from months ago. The syntax is clean though. I'll give it that.
- estimator7292 1y agoI don't really get this obsessive insistence of purging the language of null checks. (And "if(x is not null)" is not an improvement of any kind) It feels like Microsoft just wants C# to be Python or whatever and the language is losing its value and identity. It's becoming bland, messy, and complicated for all the same reasons they keep increasing padding between UI elements. It's very "me too" and I'm becoming less and less interested in what I used to consider my native language. I used to write any and all little throwaway programs and utilities in C#, but it just keeps getting more and more fussy. Like Python, or maybe java. Nowadays I reach for C++. It's more complicated, but at least it's stable and not trying to rip itself apart.
- renerick 1y ago> wants C# to be Python or whatever Oh, how happy would I be if Python had a sliver of C# features. There's nothing like null-conditionals in Python, and there are many times I miss them
- pjmlp 1y agoThat as much is true, that is why stuff like minimal APIs and now aspire came to be, they want to cater to the JavaScript and Python folks, they have said as much in a couple of .NET podcast interviews. Additinoally, I think they are becoming hostage that every year C# gets a new release, thus the team has to keep pushing features no matter what. Imagine how C# will look a decade from now with this rythm. Slowly I am starting to think it is not that bad, that most of the .NET projects that our agency does are still stuck on Framework.
- coolgoose 1y agoWelcome to PHP land :P
- _ZeD_ 1y agoWhile I can understand the reason behind the behaviour I cannot find it intuitive. If I say an asseignment I expect the value to be "evaluated". I could have grasped the expression in all the null values would have been replaced with new instances, but then it would have been too much invasive and magic to work, so - again - I understand why the designers night have been force to settle for the actual behaviour... But maybe then the half-solution is not worth it
- ivankahl 1y agoThanks for the upvotes! While testing and writing about the feature, I suspected it would receive mixed reactions. The `?.` operator behaves similarly on the LHS to the RHS, making the language more consistent, which is always a good thing. In terms of readability, I would say that once you understand how the operator works (which is intuitive because the language already supports it on the RHS), it becomes more readable than wrapping conditionals in `if` statements. There are downsides, such as the overuse I mentioned. But this is true for many other language features: it requires experience to know when to use a feature appropriately, rather than applying it everywhere. However, the great thing about this particular enhancement is that it's mostly cosmetic. Nothing prevents teams from not adopting it; the old syntax still works and can be enforced. C# and .NET are incredibly versatile, which means code can look dramatically different depending on its context and domain. For some projects, this feature might not be needed at all. But many codebases do end up with various conditional assignments, and in those cases, this can be useful.
- Archelaos 1y agoI have long desired such a language feature. It is a great addition to the language, because a single such expression helps to avoid potential bugs caused by mismatching double references in the conditional test and the execution statement of the traditional version, especially when refactoring longer code blocks. For example, if we have something like this: if (config?.Settings is not null) { ... Multiple lines that modify other settings. config.Settings.RetryPolicy = new ExponentialBackoffRetryPolicy(); } and we introduce another category SpecialSettings, we need to split one code block into two and manually place each line in the correct code block: if (config?.Settings is not null) { ... Multiple lines that modify other (normal) settings. } if (config?.SpecialSettings is not null) { ... Multiple lines that modify other special settings. config.SpecialSettings.RetryPolicy = new ExponentialBackoffRetryPolicy(); } With the new language feature the modification is easy and concise: config.Settings?.RetryPolicy = new ExponentialBackoffRetryPolicy(); becomes: config.SpecialSettings?.RetryPolicy = new ExponentialBackoffRetryPolicy(); and can be made for any other special setting in place, without the need to group them. Furthermore, I find the "Don't Overuse It" section of the article somewhat misleading. All the issues mentioned with regard to customer?.Orders?.FirstOrDefault()?.OrderNumber = GenerateNewOrderNumber(); would apply to the traditional version as well: if (customer is not null) { if (customer.Orders is not null) { if (customer.Orders.FirstOrDefault() is not null) { customer.Orders.FirstOrDefault().OrderNumber = GenerateNewOrderNumber(); } } } or: if (customer is not null) { var orders = customer.Orders; if (orders is not null) { var firstOrder = customer.Orders.FirstOrDefault(); if (firstOrder is not null) { firstOrder.OrderNumber = GenerateNewOrderNumber(); } } } If it really were a bug, when customer is null here, etc., then it would of course make sense to guard the code as detailed as described in the article. However, this is not a specific issue of the new language feature. Or to put it more bluntly: customer?.Orders?.FirstOrDefault()?.OrderNumber = GenerateNewOrderNumber(); is no replacement for customer.Orders.First().OrderNumber = GenerateNewOrderNumber(); were we want an exception on null. BTW, with the new version, we can also make the code even clearer by placing each element on its own line: customer? .Orders? .FirstOrDefault()? .OrderNumber = GenerateNewOrderNumber();
- paulmooreparks 1y agoSorry, I would flag this in a code review. It's too easy to skip past this visually. Explicit if statements make it a lot more obvious what's going on. This is too much syntactic sugar.
- jobigoud 1y agoYou must not do a lot of C# code reviews? This syntax is used in every codebase. In fact if you don't use it Visual Studio will underline it as "code can be simplified" suggestion. You've never seen something like this? MyEvent?.Invoke(sender, arg);
- paulmooreparks 1y agoI work almost exclusively in C#, and I do a lot of reviews. I'm familiar with the syntax, and I use it. It's the assignment version that I'm talking about here.
- fifticon 1y agoTo add to the chorus, IMHO this is a jumping-the-shark language feature. Having the problem this feature addresses, is a code smell. I use the ?-indexer for READING stuff, but try to limit such uses to logging and diagnostics, where they shouldn't affect actual production effects. If your C# code needs this, your "C# code" is 3 javascript files in a trenchcoat.. :-).
- SeasonalEnnui 1y agoThe thing I enjoy most about C# is the depth/levels of progressive enhancement you can do. Let's say in the first instance, you write a proof of concept algorithm using basic concepts like List<T>, foreach, stream writing. Accessible to a beginner, safe code, but it'll churn memory (which is GC'd) and run using scalar CPU instructions. Depending on your requirements you can then progressively enhance the memory churn, or the processing speed: for(;;), async, LINQ, T[], ArrayPool<T>, Span<T>, NativeMemory.Alloc, Parallel.For, Vector<T>, Vector256<T>, System.Runtime.Intrinsics. Eventually getting to a point where it's nearly the same as the best C code you could write, with no memory churn (or stop-the-world GC), and SIMD over all CPU cores for blisteringly fast performance, whilst keeping the all/most of the safety. I think these new language features have the same virtue - I can opt into them later, and intellisense/analysers will optionally make me aware that they exist.
- opticfluorine 1y agoI have occasionally, just for fun, written benchmarks for some algorithm in C++ and an equivalent C# implementation, them tried to bring the managed performance in line with native using the methods you mention and others. I'm always surprised by how often I can match the performance of the unmanaged code (even when I'm trying to optimize my C++ to the limit) while still ending up with readable and maintainable C#.
- iamflimflam1 1y agoJIT compilers can outperform statically compiled code by analysing at run time exactly what branches are taken and then optimising based on that.
- throw-the-towel 1y agoCould you please share some benchmark code? It would be incredibly useful as a learning aid!
- panzi 1y agoDoes this include the GC at the end of it all? Because if that happens after the end timestamp it's not an exact comparison. I read something once about speeding up a C/C++ compiler by simply turning free into a no-op. Such a compiler basically allocates more and more data and only frees it all at the end of execution, so then doing all the free calls is just wasted CPU cycles.
- lajr 1y agoStrange that they chose to make it `a?["b"] = c;` rather than to use the same syntax as TypeScript (`a?.["b"] = c;`). Honestly I like the C# better, and I was initially not super thrilled about the choice to include the period in the TS case, but since there is some overlap between the language design teams I assumed they would be the same.
- actionfromafar 1y agoThat would look strange IMHO. Why wouldn't it be a.["b"] then?
- jobigoud 1y agoWhere is the dot coming from? If you know the dict is not null you would write a["b"], so it makes perfect sense that the new syntax is a?["b"]. The `?` applies to whatever is to the left of it. a?.Method() has a dot because we would write a.Method(). TypeScript designers made a mistake or had other constraints probably.
- chabska 1y agoMaybe because in JS/TS, `a ? ["b"]` is a valid syntax, so they had to insert the dot to parse properly.
- dzonga 1y agoI have started playing with C#. what a pleasant language + ecosystem. .net core is above any java land web framework. both spring / quarkus. documentation is one place. and lots of it. you also get a very robust ecosystem + performance.