6 C# Mistakes Microsoft Wants You to Fix

  Рет қаралды 61,243

Nick Chapsas

Nick Chapsas

Күн бұрын

Пікірлер: 191
@IMarvinTPA
@IMarvinTPA Жыл бұрын
I prefer the Microsoft suggestion as well. I prefer more simple statements over fewer complicated ones. It is easier to read and mentally execute simple statements.
@briumphbimbles
@briumphbimbles Жыл бұрын
Absolutely! Lots of people think contrived competitive terseness is a sign of good code and it couldn't be further from the truth.
@z0nx
@z0nx Жыл бұрын
This requires you to know the implementation of `ThrowIfNull`. The coalesce doesn't depend on any implementation besides the default c# constructs. Riders suggestion wins in my opinion. But what amazes me even more is why a constructor would accept a nullable parameter and then throw immediately if the parameter is null. It's actually insane if you think about it, why are we talking about a choice that shouldn't even be a choice in the first place: push these inaccurate types up the call stack as much as possible, please!
@GregMoress
@GregMoress Жыл бұрын
Everyone who does lots of debugging agrees with you.
@IMarvinTPA
@IMarvinTPA Жыл бұрын
@@GregMoress That would be me. I appreciate me.
@temp50
@temp50 Жыл бұрын
Hm, I don't know what about you guys, but I read from left to right. It means that with the MS's way the first thing I see is "ArgumentNullException" which I don't care. Instead of seeing the name of the variable I'm trying to check.
@MaxIzrin
@MaxIzrin Жыл бұрын
I prefer Microsoft's null check. Throwing the exception in the assignment is a bit confusing.
@briumphbimbles
@briumphbimbles Жыл бұрын
Yea absolutely
@logank.70
@logank.70 Жыл бұрын
When Microsoft says, "use .Count != 0 for readability" that one is a bit subjective. I can't remember who to attribute this to, I want to say Eric Lippert (but I could be wrong), but I tend to subscribe to the "use LINQ unless you can't" mentality. Saying strings.Any() versus strings.Length != 0 could go either way. I like having typed less for LINQ and if it performs perfectly fine for my use case then there is no reason for me to change it. Sometimes LINQ makes it easy to understand what the intention was from whoever wrote it even though it may not be the most performant option. Other times it's a performance issue and you have to rewrite that section for performance reasons (and at least comment on why it is being written that way).
@brianm1864
@brianm1864 Жыл бұрын
I prefer the Microsoft suggestion. Using a guard clause makes it more readable IMO. In this case, since it's a one line method, it's simple and easy to read with the null coalescing operator, but in other cases, with other code around it, it can make for more confusing code. So I prefer to just always go the guard clause route so that I'm consistent.
@Kirides
@Kirides Жыл бұрын
Additionally to that, the suggestion also leads to less byte-code emitted, thus more compact binaries. As they make sure you don't pay the cost for "new Exception"-IL in your constructor every time an argument may be null.
@BadgersEscape
@BadgersEscape Жыл бұрын
Exactly - consistency is very valuable in any code base. You can always read and analyse code that little bit faster if everything is structured similarly.
@thethreeheadedmonkey
@thethreeheadedmonkey Жыл бұрын
In addition to @Kirides' point, if Microsoft finds some clever optimization for these methods, it's more likely to end up in the static constructor than the manual throw.
@TkrZ
@TkrZ Жыл бұрын
While I do agree that I prefer the guard clause approach, (and I know this would probably be very difficult to implement) I'd love to be able to write the following syntax: "throw ArgumentNullException when connectionString is null;". It's much more explicit in that the "throw" keyword is being used, as opposed to the actual actual throw being hidden away behind a method. It'd also be great if the aforementioned syntax supported the CallerArgumentExpressionAttribute in some way, so you wouldn't have to redundantly provide the variable name to the exception's parameters since you're already providing a variable with the "when" contextual keyword.
@lost-prototype
@lost-prototype Жыл бұрын
I think LINQ .Any is way more expressive than a not equals and a number. MS should just bake in some smart optimizations in certain LINQ implementations. (Obviously some limits depending on what's happening, but the in memory collections shouldn't be so bad)
@serbanmarin6373
@serbanmarin6373 Жыл бұрын
I agree, feels like we're going backwards with their suggestion.
@Megasware128
@Megasware128 Жыл бұрын
Well, the funny thing is if you look at the source code of Any() it already does an optimization for arrays and lists where it does basically try a count > 0
@lost-prototype
@lost-prototype Жыл бұрын
@@Megasware128 Great! So no need to change then.
@petewarner1077
@petewarner1077 Жыл бұрын
LINQ Any is well optimised these days, as are any of the LINQ operators that benefit from knowing ahead of time how many items are in the IEnumerable. I take it that the analyser is recommending it to save us an extra call or two in the call stack - which is never a bad practice - but the benefit set against changing all use of Linq.Any is arguably minimal.
@himagainstill
@himagainstill Жыл бұрын
@@serbanmarin6373 Yeah, that definitely feels like "don't use the abstraction", which is, uh, a take, definitely.
@cverde1234
@cverde1234 Жыл бұрын
Like local static functions inside a method, I would like to have local static (readonly?) variables for constant predictable allocations like the array containing the split characters because as it is promoted by the analyzer, it pollutes the class with static fields that are implementation details. string[] Split(string text){ static readonly char[] splitChars = new []{',', ' '}; return text.Split(splitChars); }
@dimitar.bogdanov
@dimitar.bogdanov Жыл бұрын
Vouch. It can be a hidden field on the class, but this is necessary.
@fishzebra
@fishzebra Жыл бұрын
always useful to keep software updated to latest frameworks and packages and treat warnings as errors before trying to write new features
@jameshancock
@jameshancock Жыл бұрын
The .Any() issue strikes me as weird because there should be overloaded extension methods for arrays (generic) and list that have optimized paths that result in the same perf directly in the sdk. Seems like a warning for no reason especially since those implementations could be inlined.
@nazarkuzo1878
@nazarkuzo1878 Жыл бұрын
@nickchapsas could you be so kind and do some performance testing to compare .Any approach on Lists/Arrays versus .Count/.Length comparisons? Since I know that .Any() does check those types and calls respective properties under the hood, so I dont think there would be such a big impact that we should sacrifice the uniform interface for collections
@eZe00
@eZe00 Жыл бұрын
@nickchapsas I agree, some performance testing would be nice. I am also under the impression stated above.
@amirhosseinahmadi3706
@amirhosseinahmadi3706 Жыл бұрын
Exactly, so weird.
@TkrZ
@TkrZ Жыл бұрын
Admittedly I'm not a Roslyn expert, but surely it should be able to detect when ".Any()" is being called on specific concrete types such as an Array and List, and essentially swap it out with ".Length / .Count != 0" during compilation?
@405servererror
@405servererror Жыл бұрын
How would the compiler know which any to call? This makes things even more weird
@MartinLiversage
@MartinLiversage Жыл бұрын
I prefer the JetBrains use of the ?? operator to throw an exception. Here it doesn't matter but in general it allows you to rewrite your code into expressions without a maze of if statements you have to wade through to determine the flow of the code. It's often easier to reason about functions calling other functions providing simple expressions as the input instead of mutation of variables and if-else blocks leading up to a function call. This reasoning is only valid if the exception is thrown as a result of truly exceptional circumstance (like in the video) and not if it's used for flow control. In general I prefer expressions over statements.
@raztubes
@raztubes Жыл бұрын
Thank you. After refactoring and implemented all these changes I have saved a total of 5ms of runtime. This will now allow me to splash around with my EF Core code. (Nice vid, though)
@KONDZiO0102
@KONDZiO0102 Жыл бұрын
7:38 There is example of beautiful API. Method (ctor) accepts nullable string but throws exception when it gets null :D
@gileee
@gileee Жыл бұрын
Well the problem is that Nullable is syntactic sugar and you could still pass in "null!" into the method. Or a more likely case you'd have some other function construct the object and pass a null into it. Non Nullable won't save you from nulls. Although I agree with you that in this example it looks like a code design problem where there should be a check for null before this function is even reached. In the case of a connection string I'd do that check as soon as it's retrieved since my apps usually strongly depend on the db being available.
@hichaeretaqua
@hichaeretaqua Жыл бұрын
Actually the CA1857 ist the id of the diagnostic description, not the analyzer. An analyzer can yield multiple diagnostics.
@haxi52
@haxi52 Жыл бұрын
I prefer the `??` null coalescing. Maybe its cause I'm used to it. But it also doesn't add another stack frame burying where the exception came from.
@DanielChenery
@DanielChenery Жыл бұрын
Personally I prefer the Rider suggestion. Throw as part of assignment, much more concise
@cdarrigo
@cdarrigo Жыл бұрын
I prefer the MFST over the JetBrains suggestion; It has the advantage of asserting the state of the inputs before executing on them.
@ICanBeWrong
@ICanBeWrong Жыл бұрын
Also, use ICollection instead of IEnumerable when you can expect a bounded collection like list or array (or another type!), but still want to keep it high level enough!
@fourZerglings
@fourZerglings Жыл бұрын
If you are only concerned about size of collection, I recommend IReadOnlyCollection
@nothingisreal6345
@nothingisreal6345 Жыл бұрын
Nice. I prefer the null coalescence operator.
@Saleca
@Saleca Жыл бұрын
I like the one liner null check, in this case is very readable and if used consistently its imo good style of programming, only care about the right side if its null so you can easily scroll up and down without clutter
@EtienneFortin
@EtienneFortin Жыл бұрын
What would be really helpful is an indication on how to structure our code to make sure the compiler can vectorize what is vectorizable. It's not clear when it can be vectorized. It change from compiler to compiler version. It's a bit of a black box unless you want to have some fun and drill down to the assembly.
@rohankumawat2870
@rohankumawat2870 Жыл бұрын
Sir, you are genius. 🔥 You saved my money to purchase new course on c#
@JinnGuild
@JinnGuild Жыл бұрын
Exception Preference - In a lot of places I have moved away from DBC and relied a lot on my DI utilizing `GetRequiredService`. It is still typical, though less common, to also be injecting values as dependencies. DBC extensions on exceptions are the most explicit. Either the built in [.ThrowIfNull[OrEmpty]], or perhaps custom contractual requirements in your own extension, which should be rare. But the main goal is to standardize across the codebase.
@solidtux
@solidtux Жыл бұрын
Ha, just made use of one of these suggestions today after watching this video. Thanks!
@nvmuzrowrihk
@nvmuzrowrihk Жыл бұрын
8:48 using a throw helper has some small performance benefit. The JIT is more likely to inline certain functions if they don't throw an exception, so not using a throw helper and throwing an exception directly can lead to the method not being inlined. At least that's what some JIT experts say. It's hard to get some sources for this and see this in action, so take this with a grain of salt.
@chris-pee
@chris-pee Жыл бұрын
It feels more likely that the throw helper will be inlined into your method (because it's small). Then suddenly your method does throw an exception, and you're back to square one. Could be wrong of course.
@TazG2000
@TazG2000 Жыл бұрын
You're describing these two options: 1 - your function gets inlined, but you call another function inside that doesn't get inlined. 2 - you don't call an inner function, but your function doesn’t get inlined. Either way, you only end up saving one function call, so what difference would it make? Also, I'm confused how this would work, because in both cases your function does throw an exception, even if it comes from an inner function call. The stack trace will report your function and the line that calls the throw helper. So I would assume that the optimization rule of "function must not throw an exception" applies to all the functions in the stack before it's caught, not just the one with the actual "throw" statement.
@aossss100
@aossss100 Жыл бұрын
​@@chris-peethrow helper is not inlined by the JIT, as far as it is recognized to be "never returns" method. This is exactly core idea behind such optimization.
@aossss100
@aossss100 Жыл бұрын
​@@chris-peeWell, there is already some confusion between "guard" methods and "throw helpers" from what I see.
@chris-pee
@chris-pee Жыл бұрын
@@aossss100 there's no confusion, I'm just dumb.
@narelehlohonolopapo9299
@narelehlohonolopapo9299 Жыл бұрын
Linear one is more readable. Both good
@drugged_monkey
@drugged_monkey Жыл бұрын
Double question mark looks more complicated to read because it used in assigment but we desided to use them in our current project. Because one-liner is one-liner)
@klocugh12
@klocugh12 Жыл бұрын
I disagree with MS on clarity of any vs length/count. IMO any for arrays/lists should be just doing this check in implementation. And arrays for split maybe could be interned.
@buriedstpatrick2294
@buriedstpatrick2294 Жыл бұрын
8:40 I prefer Rider's suggestion personally (would probably split the line before the ?? for line-length reasons though). However, it would really NEED to be a special case where I don't have control over the connection string being passed into the constructor. Because the *real* solution is obviously to not accept a nullable argument in the first place.
@mightybobka
@mightybobka Жыл бұрын
Any() and readonly static arrays should become a compiler optimizations and not performed manually. Any() is much better than Length or Count compared to zero for code readabilty.
@mAcCoLo666
@mAcCoLo666 Жыл бұрын
I still don't get why linq still has no IsEmpty method...
@lisinsignage
@lisinsignage Жыл бұрын
'Any' is semantically confusing. It's not doing what 'Any' means in regular English. Should have been named for example NotEmpty or IsNotEmpty imho, and have a Empty or Is empty.
@Max_Jacoby
@Max_Jacoby Жыл бұрын
I prefer null coalescing throw. I use it for setting default values and if there's no default value then I throw. It's consistent with that logic.
@jongeduard
@jongeduard 11 ай бұрын
Yes, but my preference with those things tends to change when I am using the parameter more than once in the same function, often when the function is also of a longer or more complex type, and often more imperative in style. But with shorter, often already more expressive kinds of code, you're probably also going to prefer a lot more coalescing or ternary operators, or maybe even switch expressions and pattern matching syntax. So in other words, for me it depends on context.
@modernkennnern
@modernkennnern Жыл бұрын
The .Any() change states "for clarity". Personally, I don't think the intention is as clear with "Length is 0", but the performance is obvious. Regardless, I will follow whatever Analyzer they add.
@mAcCoLo666
@mAcCoLo666 Жыл бұрын
It may be more readable for empty-collections checks. But at that point just add an IsEmpty to linq already.
@killymxi
@killymxi Жыл бұрын
Type narrowing that is spread across multiple statements without introducing new variables is less readable than one expression in my opinion. And at this point I'm more familiar with throw after ?? that was introduced earlier than with static methods on exception classes. That being said, I have no strong opinion between these two and would choose the one that is more fitting in each particular case. Got a chain of assertions - use cleaner ones when available. Only have to deal with null - ?? is fine and easy to replace with something like null object pattern/Option monad when necessary.
@davidwilliss5555
@davidwilliss5555 Жыл бұрын
I like the suggestion shown for value.ToLower() == otherValue.ToLower(). I see that one all the time, especially in code that I wrote several years ago.
@emmanueladebiyi2109
@emmanueladebiyi2109 Жыл бұрын
Amazing video, as always!
@BadgersEscape
@BadgersEscape Жыл бұрын
In the exception case, there are multiple possible reasons for Microsofts suggestion, but I find the most probable one to be async methods. If your method is async, then you don't want to throw in that same method - you want to move the throw itself to a separate helper method because that will simplify the code generated by the compiler for async state machines. Given that you have a strong reason to do this in async methods, it makes a lot of sense to go for consistency and do it in all methods. As an aside, if you really want to you can combine the two methods (by making the throwing helper method generic and have a generic return value - which will compile because the compiler ignores the lack of actually returned value since you have a throw in there instead - case in point the classic NotImplemented boiler plate code). However personally I prefer the MS recommended way more because it looks _a lot_ cleaner when you have multiple checks at the beginning of your method. In general you are probably checking a lot of other stuff than just guarding against null, so if would not look as clean to mix-and-match the two different syntaxes.
@jessecalato4677
@jessecalato4677 Жыл бұрын
I've been actively using the Rider suggestion for a while now. I think I'm going to test the MS suggestion out though.
@martinl9574
@martinl9574 Жыл бұрын
In case of assignment, I prefer the Rider suggestion. In case of arguments that will not be assigned directly to a field, i prefer the Microsoft suggestion. This way you have one line for each argument regardless of the later usage.
@ImYnotplay
@ImYnotplay Жыл бұрын
I think the rider suggestion is better, as you can be flexible with the exceptions you're throwing. This is because where I currently work we define our own exceptions (mapping them accordingly) to be more easily aware of which layer they're coming from.
@DEZK90
@DEZK90 Жыл бұрын
In that case you can add the exact same thing to your custom exceptions. MyExceptions.ThrowIf() or something like that. It's the same as any other Guard pattern which is way better than having two very different branches and one "assignment" in one line. When debugging code later you will be happy for every line that is written as simply as can be.
@ImYnotplay
@ImYnotplay Жыл бұрын
@@DEZK90 Fair point, though I also feel like we'd not use it in that way enough to compensate refactoring it immediately as a guard pattern (due to the exceptions being very specific), however, it's something I'll keep in mind from now on.
@arabn696
@arabn696 Жыл бұрын
Hi Nick! I plan buy all your courses, but I didn't on time use a promotion code... when will be next ocasion? 🙂
@IllidanS4
@IllidanS4 Жыл бұрын
For emptiness check I would prefer "arr is not []" or maybe "arr is not { Count: 0}". I am all in for patterns! As for ArgumentNullException, I don't like either approach. Instead I think this would be the best: _value = ArgumentNullException.Validate(value); // always returns non-null or throws Such a method does not exist yet, but this approach does not require writing the name twice.
@bd73ne
@bd73ne Жыл бұрын
I prefer Microsoft’s recommendation. A video (or series) idea - c# has many new features and better ways of doing things. It would be neat to see the old vs. new methods.
@DavidWengier
@DavidWengier Жыл бұрын
It might have changed in recent JITs, but I believe methods that throw will not be inlined, so ArgumentNullException.ThrowIfNull has a slight perf advantage in some cases, over the pure code style suggestion of using the null coallescing operator. Roslyn offers both, but only one has been turned on by default in the SDK. In fact, I don't think any code style analyzers are likely to be turned on automatically int he SDK.
@jongeduard
@jongeduard 11 ай бұрын
Taking a look at 6:43 in the video. Why did they never add static local variables to the language?? Even C and C++ have that! Then you can still keep the thing nicely encapsulated inside just 1 method, while it's lifetime is going to be of the entire duration of the process. Just like you can have local constants and static local functions. Moving variables into fields while you only need them at 1 point in the code is a bit of a code smell in my opinion.
@krissam7791
@krissam7791 Жыл бұрын
Regarding the not null version, I would honestly prefer if c# had some syntactic sugar that provided an Unless (condition) statement, which would effectively be an if (!condition), and then do Unless (argument is null) { ... } else { throw ... }
@billy65bob
@billy65bob Жыл бұрын
11:45 I'd be curious to know how the one reacts to plugin APIs. The Jetbrains one commonly triggers for the way we've approached it in this case, for example it'd warn with messages like 'Suspicious Cast: There is no type in the solution which is inherited from both IPluginInterface and IGraphicalPluginInterface'.
@MilYanXo
@MilYanXo Жыл бұрын
Isnt the Micosoft way slower with multiple parameters? The ?? operator keeps the value optimized and ready for assignment, if you first check it then assign it later, it needs to be loaded again. The IL should reflect this.
@Osirus1156
@Osirus1156 Жыл бұрын
Whilst I agree with the speed of using length instead of any I don’t agree that it’s more clear. I think .Any() is extremely clear.
@Pouya..
@Pouya.. Жыл бұрын
As always thanks for all this info... I rather use Microsoft suggestion as it is more clear simple and simple as an English sentence instead of weird looking if 😅
@Dominik-K
@Dominik-K Жыл бұрын
I would go with the MS suggested one for the parameter checking
@DaddyFrosty
@DaddyFrosty Жыл бұрын
I like the Microsoft one, but I will only use it is Aggressively inlined. Cleaner trace + no jump, aka better perf.
@garcipat
@garcipat Жыл бұрын
Since there are nullable types, the checking null is either not required. But in case of modules we didnt migrate yetvi created an extension that wraps the second nullcheck in one.
@PavelMikula
@PavelMikula Жыл бұрын
Do you know SonarLint extension from Sonar? It brings bunch of analyzers and I think there were rules for some of these cases.
@briumphbimbles
@briumphbimbles Жыл бұрын
How on earth is the Any method not implemented as Length > 0 (or as it suggests != 0)?
@alexandernava9275
@alexandernava9275 Жыл бұрын
I would go with Microsoft’s suggestion as it is more inline with a Guard, likewise if you have more than one the Microsoft way scales where riders wouldn’t
@F1nalspace
@F1nalspace Жыл бұрын
Very interesting, but only the constant expected as unkwown for - everything else i did knew. About your question if we use ?? ArgumentNullException() -> Yes we do use this, but only in very simple cases. We dont use ArgumentNullException.ThrowIfNull() because i assume that it is a function call, so when it throws the exception it is thrown inside that function and not on call site.
@jackkendall6420
@jackkendall6420 Жыл бұрын
I really, really, really disagree with the idea that .Length != 0 is clearer than .Any(). The entire point of LINQ is to abstract over the awfulness of manually dealing with the sizes of collections! And there's plenty more room for typos -- you will get a compilation error if you write .Azy(), but not if you write .Length == 0 or .Length != 1. I personally prefer to go even further and add a .IsEmpty() extension method for this scenario.
@kamilmikua5794
@kamilmikua5794 Жыл бұрын
Hey, as always great content, but you may add some chapters to the video for better feeling :)
@shoooozzzz
@shoooozzzz Жыл бұрын
When are you going to switch to the new Rider UI?
@amirhosseinahmadi3706
@amirhosseinahmadi3706 Жыл бұрын
The `.Any()` warning is so strange. LINQ methods usually check for the type of the collection and use the most efficient way of performing the operation (in this case checking if the array contains an element) based on the type of the collection automatically. Any() should be optimized to do the same sort of thing here, instead of telling developers to change their code. And I wholeheartedly disagree that `.Length != 0` is better in terms of "clarity" than `.Any()`; it's absolutely not.
@raztubes
@raztubes Жыл бұрын
Yes, but this way you're avoiding that check. This is pretty much the only difference.
@garcipat
@garcipat Жыл бұрын
Most of the time i dont have costants passing into methods. Otherwise you could use the constant in the method directly or define it there.
@cdarrigo
@cdarrigo Жыл бұрын
Please do a video on ConfigureAwait()
@jazalex
@jazalex Жыл бұрын
Actually ".Any()" is optimized internally for lists and arrays, it will simply use the "count" field if available
@microtech2448
@microtech2448 Жыл бұрын
Hi, which IDE you are using?
Жыл бұрын
These are pretty good suggestions. I'm just surprised this was not in the .NET before. Good stuff. Can I make my own analyzers that will trigger automatically on compilation on my project? Like project specific linter?
@nickchapsas
@nickchapsas Жыл бұрын
Absolutely. You can even write your own with your own refactoring
@jessecalato4677
@jessecalato4677 Жыл бұрын
@@nickchapsas Do you have a video on wrting analyzers?
@br3nto
@br3nto Жыл бұрын
4:33 comparing against .length isn’t clearer. And why does .length have to be more performant? Semantically, .Any() is preferable and clearer, so really they should make that more performant.
@DanteDeRuwe
@DanteDeRuwe Жыл бұрын
I personally like ?? when throwing argumentexceptions, but only if the assignment is obvious (like in the constructor with DI). I personally dislike it in the case of, for example, `variable?.Property1?.Property2 ?? throw...`. Then I would rather use a separate statement that throws the exception.
@leviathan5792
@leviathan5792 Жыл бұрын
Reading the other comments, it seems my opinion is somewhat controversial. I prefer the null-coalescing throw over the ThrowIfNull. This is mostly because of type safety - when using ThrowIfNull, were assigning a nullable variable to a non-nullable variable (that code isn't ever reached if the variable really is null, but it bothers me), while using the null-coalescing operator is more like "collapsing" the nullable type into a non-nullable type. However, I do think that ThrowIfNull is much more beginner friendly.
@gileee
@gileee Жыл бұрын
True. It's also cleaner if you have multiple fields being initialized like this, some of which might have a "?? [some default value]" instead of a throw.
@br3nto
@br3nto Жыл бұрын
8:35 preference is the ?? Operator. However, ?? only checks for null. I’d ultimately want an operator that checks for null or empty. I’d also hope that a string containing only whitespace is empty, otherwise I’d also want a property similar to presence in Ruby.
@gileee
@gileee Жыл бұрын
You have a .IsNullOrWhiteSpace already. Empty shouldn't be true in a whitespace only string imo, since I basically expect it just do a "string.Length > 0" check. If you want a trimmed string then trim it.
@bslushynskyi
@bslushynskyi Жыл бұрын
I would go with Microsoft suggestion on ArgumentNullException dealing. Lines of code are shorter, more readable
@gileee
@gileee Жыл бұрын
I put the ?? onto a new line so it's basically the same number of columns.
@ElOroDelTigre
@ElOroDelTigre Жыл бұрын
I saw the thumbnail and read "Microsoft says: fix cheese" and I began to worry.
@SecondFinale
@SecondFinale Жыл бұрын
It would be nice if these were compiler optimizations, instead.
@br3nto
@br3nto Жыл бұрын
2:43 I don’t understand ConstantExpected. Why is a constant note performant? Isn’t the const value copied anyways?
@jacobphillips9235
@jacobphillips9235 Жыл бұрын
i used `_example = example ?? throw new ArgumentNullException(nameof(example));` today at work. it just feels natural to coalesce into a new exception. i use it often after an efcore query `var example = await _dbContext.Users.Where(u => u.UserGuid == userGuidUriParam).SingleOrDefaultAsync() ?? throw new KeyNotFoundException();`
@JonnyItunes
@JonnyItunes Жыл бұрын
For readability, I prefer the ThrowIfNull()
@DasBloch
@DasBloch Жыл бұрын
I did not now about the performance of any. I have just made this extension public static bool Any(this List collection) { return collection.Count != 0; } Lists will automatically chose the extension Any() over the linq Any()
@ThunderChasers
@ThunderChasers Жыл бұрын
I prefer the Microsoft suggestion. It is more concise.
@justwatching6118
@justwatching6118 Жыл бұрын
Microsoft suggested one, for readability. But also, I'll instead of that use string.IsNullOrWhiteSpace (which I use in many scenarios)..
@TheMikernet
@TheMikernet Жыл бұрын
"Microsoft uses it [ConstantExpected] quite a bit internally actually" - like where? The only place I'm aware it is used is hardware intrinsics because codegen is shit without a constant. I don't know why it would be needed anywhere else.
@usernamename2978
@usernamename2978 Жыл бұрын
Listening is hard work
@tomashubelbauer
@tomashubelbauer Жыл бұрын
IMO the .Any warning is a straight up failure of the SDK/compiler to optimize stuff correctly. The clarify of .Length !== 0 vs. .Any is debatable at best and the performance aspect should be a nothing-burger in terms of the performance difference and if it isn't Microsoft should get to work making it one instead of introducing warning. Very weird suggestion this one.
@DotNetDemon83
@DotNetDemon83 Жыл бұрын
“Hey what the hell are you doing?” -My IDE every single day
@dsalodki
@dsalodki Жыл бұрын
I learn rust now. Before worked with c#. Really advanced and modern Rust. Weird c#.
@user-tk2jy8xr8b
@user-tk2jy8xr8b Жыл бұрын
Why isn't there still a static Any overload for a string and other types?
@aossss100
@aossss100 Жыл бұрын
Use "throw helpers", suggested by Microsoft, is not only maintainability improvement. It is considered to be performance improvement as well. ☝️
@SvdSinner
@SvdSinner Жыл бұрын
The .Any() surprised me a bit since ReSharper has routinely suggested changing .Length == 0 to .Any() for years now
@gileee
@gileee Жыл бұрын
Because.Any() will call ".Length > 0" for Lists and Arrays anyway.
@josephizang6187
@josephizang6187 Жыл бұрын
❤❤❤ thanks nick
@PavelMikula
@PavelMikula Жыл бұрын
I prefer the ?? one, especially when there's more than one dependency to inject.
@maurosampietro9900
@maurosampietro9900 Жыл бұрын
I would use null coalescing assignment with .Throw if it exists. So not to check for null twice
@KingOfBlades27
@KingOfBlades27 Жыл бұрын
Wait. Using sealed in your classes makes your code actually perform better?!?!
@serus164
@serus164 Жыл бұрын
So microsoft is trying to make its own vs integrated resharper?
@Bliss467
@Bliss467 Жыл бұрын
I'd probably prefer text.Any() over text.Length != 0 unless it's a library method, just because it's cleaner and simpler.
@AvenDonn
@AvenDonn Жыл бұрын
I've had cases where the suspicious cast warning was a false positive. I think it's because it didn't know about something
@simonwood4864
@simonwood4864 Жыл бұрын
Doesn't the compiler do these optimizations anyway?
@nickchapsas
@nickchapsas Жыл бұрын
Absolutely not
@gileee
@gileee Жыл бұрын
Not that it couldn't if we're being honest.
@proosee
@proosee Жыл бұрын
This is a bit too far at some points for my taste. E. g. changing to static readonly field from new [] can degrade readability at some cases - I get the performance gain, but shouldn't we have something to say "hey compiler, this method won't mutate an input table, so if anyone is passing an array that is using initializer and is not modified in code elsewhere then just convert it to a constant".
@dhollm
@dhollm Жыл бұрын
Swapping Any() for Length or Count seems like premature optimization to me. Unless its performance critical I prefer the more general approach. Using Any() will also allow for easier refactoring later.
@briumphbimbles
@briumphbimbles Жыл бұрын
You are prematurely optimising for refactoring. Functionality -> Legibility -> Performance -> Extensibility -> Anything other concerns (including refactorability). I would argue they are equally as legible so Performance trumps refactoring. NOTE: legibility and Performance are interchangeable depending on the task at hand but this is the normal order.
@z0nx
@z0nx Жыл бұрын
@@briumphbimbles Aren't most people writing data munching APIs? Code performance is rarely a thing there
@briumphbimbles
@briumphbimbles Жыл бұрын
@@z0nx Code performance is always a thing. It doesn't take much for someone who doesn't know what they are doing to max out even a modern computer with an O(n!) algorithm. We are constantly writing code with a background understanding of the best ways to mitigate the most egregious performance issues. Even if we aren't nursing it to squeeze every CPU cycle.
@z0nx
@z0nx Жыл бұрын
@@briumphbimbles As someone else mentioned, things like .Any() already does a typecheck to rule out most of these issues. Focusing on these things instead of the actual domain issue at hand seems like a waste of time, honestly. performance < refactoring. Use the time not spent figuring out complex optimized code to find the bottlenecks that do require attention.
@briumphbimbles
@briumphbimbles Жыл бұрын
@@z0nx Why do you need a type check to count how many items are in a collection? Or rather check if the length is > 0? What has a type check in Any got to do with writing crappy unoptimised code?
@bulwarkjm2
@bulwarkjm2 Жыл бұрын
8:44 Microsoft suggested way. More readable.
@scuroguardiano9787
@scuroguardiano9787 Жыл бұрын
Microsoft way of null check is better IMO, it is far more readable and clean.
@michaelnjensen
@michaelnjensen Жыл бұрын
I prefer Riders suggestion tbh, the MS one seems off for me, somehow.
@aj.arunkumar
@aj.arunkumar Жыл бұрын
i prefer the microsoft suggested one instead of rider suggested one for argumentNullException, because the latter makes the code too long horizontally and looks like too many things are going around with ?? and all..
@gileee
@gileee Жыл бұрын
It doesn't have to be on the same line. Put the ?? on a new line and it's fine. Although if you see "?? throw" do you really need to see the new Exception that's following it? You know it's there and what it's doing.
@aj.arunkumar
@aj.arunkumar Жыл бұрын
@@gileee at that point we are left with two lines and I would argue that having the old way of using if statement as guard clause is better.
@gileee
@gileee Жыл бұрын
@@aj.arunkumar Except you can chain more logic with ??. It'll also look the same if some fields are required and have a throw or have a default value. It also looks more similar to and is easily replaced with Maybe/Option/Optional monad if you ever wanna refactor in that direction. Not even mentioning that you can change the Exception type and message right there and so on. But honestly it really doesn't matter. It's like thinking endlessly on how a variable should be named, it really isn't that important at the end of the day.
Жыл бұрын
Coalescing with throwing exception brings back memories of PHP 'or die()'. I was never fan of that. I prefer null coalescing only for really coalescing nulls.
@adamsbart
@adamsbart Жыл бұрын
well, all day long I would go with null-coalescing operator instead of the microsoft guard option, much cleaner and what's more important, oneliner :)
The NEW Way of Validating Settings in .NET 8
9:12
Nick Chapsas
Рет қаралды 35 М.
The New Way of Parsing ANY Type in .NET
13:03
Nick Chapsas
Рет қаралды 70 М.
ROSÉ & Bruno Mars - APT. (Official Music Video)
02:54
ROSÉ
Рет қаралды 243 МЛН
КОГДА К БАТЕ ПРИШЕЛ ДРУГ😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 6 МЛН
Yay, My Dad Is a Vending Machine! 🛍️😆 #funny #prank #comedy
00:17
The 3 Biggest Mistakes of Object Mapping in .NET
11:33
Nick Chapsas
Рет қаралды 64 М.
PrintWriter and FileWriter - Writing to Files in Java
42:17
Peter Arsenault Industries
Рет қаралды 25
What’s the Result Type Everyone Is Using in .NET?
14:47
Nick Chapsas
Рет қаралды 111 М.
I WON!!!!! I WON!!!!!!!!!!!!!!
32:29
GothamChess
Рет қаралды 444 М.
Athenians overview (AoE2)
11:38
Spirit Of The Law
Рет қаралды 87 М.
3 .NET "Best Practices" I Changed My Mind About
10:16
Nick Chapsas
Рет қаралды 104 М.
Apple, Stop Putting Things On the Bottom Please
9:16
TechLinked
Рет қаралды 529 М.