"Stop Using null, Use default Instead in C#" | Code Cop

  Рет қаралды 64,345

Nick Chapsas

Nick Chapsas

4 ай бұрын

Check out my courses on Dometrain: dometrain.com
Become a Patreon and get special perks: / nickchapsas
Hello, everybody, I'm Nick, and in this video, I will go through some really bad advice telling you that you shouldn't use null in C# but instead, you should be using the default keyword.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elfocrash
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 190
@maschyt
@maschyt 4 ай бұрын
Instead of `Enumerable.Empty()` or `Array.Empty()` since C# 12 we can also use `[]` to denote an empty collection which will be compiled down to the same.
@garcipat
@garcipat 4 ай бұрын
There was also something even berrer performing he showed in a video but dont remember that it was. Domething that is only compiled once by the compiler and done.
@jamesreynolds3167
@jamesreynolds3167 4 ай бұрын
Just using [] leads to the same issue described in this video. We don't know the type when just reading the code. We then have to look at the return type of the method to know what we're returning. I think Array.Empty and Enumerable.Empty is best since it describes its type.
@maschyt
@maschyt 4 ай бұрын
@@jamesreynolds3167 that depends if the specific type is relevant or if you only care to know that a collection is returned. In the latter case just returning [] may be fine to denote that an empty collection is returned. As mentioned in the video the issue with `default` is not so much that you can’t immediately see the exact type it, but mostly that you can’t immediately see the value that gets returned. Because for this you need to know if the type is a reference type, nullable value or type or non-nullable value type, and some more. This is less of an issue with [] where you can immediately see that the return value is an empty collection.
@jdsaravaiya6468
@jdsaravaiya6468 4 ай бұрын
​@@garcipatits Enumerable.Empty()
@zagoskintoto
@zagoskintoto 4 ай бұрын
I'm glad you showed returning an empty enumerable. Returning nullable IEnumerables triggers my ocd
@vivekkaushik9508
@vivekkaushik9508 4 ай бұрын
You need some fentanyl to chill out dude. 😂😂
@djp_video
@djp_video 4 ай бұрын
But there is a difference between an empty result and an unavailable result. That's why we return nulls -- to indicate that the requested data isn't available -- not just that there aren't any results. I'd much rather know that "the data you want isn't available now" instead of "there is no data that matches your request." The most common alternative, throwing an exception, is a bad idea. It kills performance and eats up a lot of memory generating the exception object, error message, and a stack trace that is not likely to be used.
@zagoskintoto
@zagoskintoto 4 ай бұрын
@@billyhagood6014 I would check for null if the signature said it could be null, I don't get where you are coming from. Just because I don't like implementing returning a null collection, because I believe it adds 0 valuable information, doesn't mean I don't work around how others implement their stuff.
@Crozz22
@Crozz22 4 ай бұрын
Whenever I see Task I think that the method should really have been a IAsyncEnumerable
@orterves
@orterves 4 ай бұрын
A domain model that uses null as a special value for an enumerable compared to using an empty should be revised. Null has a very niche purpose, every other use was a billion dollar mistake that is better served by types like Result and Option
@AlexBroitman
@AlexBroitman 4 ай бұрын
Agree. Returning default when you know the type is bad. In addition I don't like to check Any() as in the example. Any() causes multiple enumeration. I always try to avoid using Any(). For example Map(...) method should return empty sequence for empty input sequence, so no need to check Any() at all.
@aldul728
@aldul728 4 ай бұрын
The main place where I see the default keyword being used and recommended by MS is in Blazor, where you give injected properties default values to imply that they will be injected by the framework and you don't expect them to be null anyways.
@mortenthomas3881
@mortenthomas3881 4 ай бұрын
Hi Nick, I love that you not only talk a bad advice down - you also show us that your own code could be better (returning an enpty collection instead of null)
@Erik_The_Viking
@Erik_The_Viking 4 ай бұрын
Great video with examples of when and when NOT to use defualt or null. I never understood why people try to overcomplicate things.
@jsonk
@jsonk 4 ай бұрын
Starting C#12, you can simply use "return [];" to return an empty enumerable which is extremely nice and less wordy. This would expand to "return Array.Empty()," which "Enumerable.Empty()" uses under its implementation.
@dnwheeler
@dnwheeler 4 ай бұрын
I agree 100%. A nullable return type means it will return a value or a *null*, not a value or a default. Returning a null is semantically correct.
@fredericbrown8871
@fredericbrown8871 4 ай бұрын
I absolutely agree, returning default makes the intent less clear and could even introduce a bug in some generic methods that takes both reference and value types (e. g. return default in a async Task, that will return null for reference types and a non null value for a value type). IMHO, you should only use default when you want to get the default(!) value of a type, never because it incidentally is null for a reference type and you want to return null. And yeah, I would normally return an empty sequence when the methods represents a query that can return none, a single or several items. I try to use null only to express "there is no value" and a nullable return type to express "this method might return a value or not", which hasn't the same meaning than an empty sequence in my mind.
@NZTritium
@NZTritium 4 ай бұрын
good tip on returning the empty enumerable.
@winchester2581
@winchester2581 4 ай бұрын
Honestly, I was waiting for this tip nervously, but in the second half of the video it went OK Nick did a great job of explaining about null vs default thing
@mikejs2004
@mikejs2004 4 ай бұрын
I’ve killed PRs over someone not returning enumerator.Empty() when the return type is obviously an IEnumerable. Really grinds my gears.
@bilalakil
@bilalakil 4 ай бұрын
I use default for generic returns, and also when I want to return a null-like struct (which will usually be accompanied by an IsSet property or something like that which would return false for the default value). I'd rather use default than calling the default constructor or making a dedicated method for returning a null-like version of the struct. I'm happy to use Array.Empty but I don't like Enumerable.Empty because there's no .Count or .IsEmpty property on an enumerable - you'd have to actually create an enumerator to find out whether any objects exist in the enumerator or not. So, for enumerators specifically, I return null.
@mrgc1024
@mrgc1024 4 ай бұрын
Enumerable.Empty() returns an instance of EmptyPartition. It implements the IIListProvider interface's GetCount(bool) method that simply returns 0. The Any() method will not create any enumerator if the type implements one of the following interfaces: ICollection (uses .Count property), IIListProvider (uses .GetCount(bool) method), ICollection (uses .Count property). So you can return Enumerable.Empty() and can use the Any() method to check if it contains any element without creating any enumerator.
@bilalakil
@bilalakil 4 ай бұрын
@@mrgc1024 Thanks for this info! That’s pretty deep and I didn’t know 😂 So many layers, hard to keep up with..
@jhdk356
@jhdk356 4 ай бұрын
Here is a funny one (if my memory serves me well): int? a = !string.IsNullOrEmpty(str) ? int.Parse(str) : null; // fails, as the compiler cannot find a common type for int and null int? a = !string.IsNullOrEmpty(str) ? int.Parse(str) : default; // in this case, default becomes 0 and not null, because when determining the type of the ternary operator result, it decides that int will work, and default(int) = 0 int? a = !string.IsNullOrEmpty(str) ? int.Parse(str) : default(int?); // This works, as the compiler now decides, that the return type of the ternary operator is int?, which matches the return type of both int.Parse() and default(int?), hence default(int?) becomes null
@MrMediator24
@MrMediator24 4 ай бұрын
Last one is almost Result/Option from Rust, tagged unions. Probably one of the best ways to handle errors since it's clearly and cleanly separates which functions fallible and which not
@karlpickett6035
@karlpickett6035 Ай бұрын
It makes sense to return a null instead of empty enumeration, if you want other functions to not accept the empty / null value. That makes it a compile time fail instead of a runtime fail/check. For example, calling LogTransaction() on an empty enumeration probably doesn't make sense.
@Igahwanoiar
@Igahwanoiar 4 ай бұрын
This is what the maybe monad is for! (Or optionals, but that is an ambiguous term in other languages.) The main question here is, how do you communicate what happened? Or better yet, how do I provide the caller of the function with enough information to know what to do next? And both null and an empty list will not tell you this (without explicitly stating it in the documentation). The only way you can do this, is by showing it in the method signature. By returning a maybe, it unambiguously states: this method can go well, in which case it has a value, or you have an error. The error is an enum or a custom class that will allow the caller to determine what to do with this error. (Please don't throw an exception; that terrible for performance and software stability!) Some implementations of maybes in C# actually use a collection with 0 or 1 value, so you can just use linq to chain the calls together in your business logic using linq. A match made in heaven! Your business logic becomes a one liner and your code never crashes. (It just takes some getting used to.)
@brianviktor8212
@brianviktor8212 4 ай бұрын
I will continue to return 'null'. I return 'default' only in cases where I use generic types. I only follow advice I agree on, and using default over null is not it.
@PierreH1968
@PierreH1968 4 ай бұрын
Thank you, Great Advice!
@jasoncox7244
@jasoncox7244 4 ай бұрын
For Enumerables returning Empty is definitely the right way to go; but how about when you're returning a single instance of a struct type. I tend to distinguish between `AStruct?` and `AStruct` and return `null` explicitly to indicate that the requested item does not exist (as opposed to `default`) where it is appropriate. [E.g. a "NotFound" result]
@AbhinavKulshreshtha
@AbhinavKulshreshtha 4 ай бұрын
This is how we do it in my office, everything is in a list. I found it bad initially because in many places, I knew we only have one item to send, but eventually i realised its benifit on a large scale project.
@7r4k1r
@7r4k1r 3 ай бұрын
In the "GetBankDetails" example we could have easily avoided the "if" completely, instead of explicitly returning an empty enumerable, because the result is only being mapped - which should be an operation without any side-effects. When it comes to the "AClass" example at the end, I really like the new "require" modifier which makes the ugly "null!" or "default!" assignment a thing of the past. As always thanks for the videos, officer. :)
@TheOnlyDominik
@TheOnlyDominik 4 ай бұрын
Agree, use null! There is a difference between returning a result e.g. database query e.g. empty List (Good, but no Match) or null (Error).
@aragorntjuh
@aragorntjuh 4 ай бұрын
I like the Enumerable.Empty suggestion, will start using that from here on out
@obiwanjacobi
@obiwanjacobi 4 ай бұрын
I use default only with generics. Agree on returning non-null (empty) values as much as possible - also think of returning and empty string instead of null. Next video: if (obj == null) - or - if (obj is null) 😉
@hernanar3647
@hernanar3647 4 ай бұрын
The video about "X == null" or "X is null", is the null checking evolution I think
@TrostanYT
@TrostanYT 4 ай бұрын
He already has a video on this kzbin.info/www/bejne/raKnip1ml8qSpck
@michaelkhalsa
@michaelkhalsa 4 ай бұрын
For ienumerables, return null if error and empty if none For string, return string.empty, but always check for is null or empty when consuming. For values types, return 0, etc. then in the rare cases where you need a nullable value type, it is not lost in meaning. Keep nulls out of the database, except for dates,I.e., always set a default on fields in database itself.
@NateRocks
@NateRocks 4 ай бұрын
I'm so glad you pointed out the advantage of doing Enumerable.Empty! If only more people realized this.
@anonimxwz
@anonimxwz 4 ай бұрын
I think empty data struct is the best for methods that return a data struct like a list, null for single item which are nullable and default for the others.
@rafazieba9982
@rafazieba9982 4 ай бұрын
A null and an empty collection are two different things. In this case you should return an empty collection but this is not always the case. E.g. if you have a method that accepts a parameter to search by and you want to return a related list (you want to return all post posted by a given user) then an empty collection means no post authored by this user but null means there is no such user. The example is not perfect because you should probably use an exception or some Optional or Result type here instead of null but nulls are useful. A null and an empty string are two different things. Don't throw ArgumentNullException if string.IsNullOrEmpty like Microsoft does in some cases.
@ErazerPT
@ErazerPT 4 ай бұрын
Do agree with the first part, not so much with the second. If you return "something empty" so that "poor lill baby coder" doesn't have to null check, you now can't tell whether or not it was really an empty result set or, erhmm, null. That said, if performance isn't "cycle and or byte critical", i rather use a message passing class that carries the result, status of operation and some info. Sure, there's a memory and performance hit, but for some environments, actionable information will always beat a few ms and MB.
@CRBarchager
@CRBarchager 4 ай бұрын
I completely agree with you, Nick. This is terrible. You basically need to think twice of that is returned and have to know what ever type result to from a its default value. I'm always try to get rid of null when ever possible as to lower the need for null checks. Better to have an empty array or list so the calling method can just go and interate over the collection when it's returned even with 0 items.
@ivanp_personal
@ivanp_personal 4 ай бұрын
Totally agree with Nick.
@a__guy
@a__guy 4 ай бұрын
no mention of new required keyword when talking about “= null!” and “= default!” 😢
@fifty-plus
@fifty-plus 4 ай бұрын
Yeah, or init-only properties. I guess to limit the scope of the video as they're touched on in other of his videos.
@joshpatton757
@joshpatton757 4 ай бұрын
IMO, there are a few places where either 'default' or 'default(T)' is the right way to go: You already brought up generics, there's also a few patterns where it makes more sense such as 'try...catch', where you won't expect to use the value returned if the try fails. In this case, the explicit null/zero/whatever is a distraction because in the normal usage we are going to ignore the value returned, and thus do not care. Using 'default' hints at that. default vs default(T) is more about readability in my opinion - use default only if what you are going to be returning is explicitly obvious from context, or when in normal usage you do not care about that result. Fully agreed that returning null collections of any stripe are problematic, I can't count the number of times where I've inherited code with that particular landmine.
@garcipat
@garcipat 4 ай бұрын
I mostly use it in default values of a method if argument is optional but i want it prefilled
@kiwiproductions4510
@kiwiproductions4510 4 ай бұрын
I would love it if somewhere for things like classes I could define what 'default' actually is.
@user-hb7py7xy7b
@user-hb7py7xy7b 4 ай бұрын
Null for me is more expressive for reading. Also if we dealing with non-reference types I found it more ambiguous: is default value was returned because it's supposed to be default or it was returned as a result of internal check according to business logic?
@iSoldat
@iSoldat 4 ай бұрын
My preferences are returning default(T) when building generics, the Enumerable.Empty when returning enumerable generics, and null when expecting a single result.
@ocin_the_ocin8766
@ocin_the_ocin8766 4 ай бұрын
this has changed my life
@kurokyuu
@kurokyuu 4 ай бұрын
I mainly use the default cause for me it's nicer, and for collections I've learned from another video from you, that'll return a empty result with Enumerable.Empty or Array.Empty is a good thing, which made really sense. For the default case I understand the argument and can see where someone can have issues I didn't think about especially if you're working in a team where not everyone understands this. Still I'll use default anyway, but the advise itself on this linkedin page is in general dumb as many of these "advises". Since we've got pattern matching I also use something like this: if(item is { }) instead of if(item is not null) or if(item != null), I think the object notation is a bit more beautiful, since in pattern matching you'll eventually also use something like if(item is {IsValidated: true, Date.Year: > 2022}) so it's a bit more consisting but this can be confusing too. At the end of the day it's often a personal think.
@DanimoDev
@DanimoDev 4 ай бұрын
Agreed. There is a lot of null hating atm, and some of it is valid when paired with the context, for example using the result or null object pattern instead of returning nulls, or returning empty enumerable instead as you suggested. Of course there are better practices than returning null when appropriate, doesn't mean it is the general rule. The problem I find is that people take the sentiment too literally and apply it to all cases and that it is bad practice, which generally isn't true. I partly blame some of the sensational click bait content creators use in their videos/articles like "DON'T DO THIS" with a picture of something everybody does. Usually a completely false statement until you watch the video in full and understand in what context they are applying the statement too.
@Thial92
@Thial92 4 ай бұрын
Imo default should only be used for initialization of nullable types when using var like "var something = default(SomeDto);" because you might only want to assign the actual value based on a condition, or "var something = default(T);" when you are handling generics. Using default to assign actual values as in for example "return default" or "something = default" can be highly misleading and dangerous.
@tanglesites
@tanglesites 4 ай бұрын
That is a little crazy! I was just talking about this yesterday! I even tweeted it... X'ed it... whatever. My question wasn't so much about returning default in methods, I build API's and we do that here, ... it was more about assigning it to variable definitions. Stack Overflow said to use default, but others have said null is better. So I was just wondering. This kinda answered my question. Great video Nick.
@parlor3115
@parlor3115 4 ай бұрын
Why not pass "entities" as is to the mapper? Or amI missing something?
@narumikazuchi
@narumikazuchi 4 ай бұрын
I just want to correct something (if I understood Nick correctly here). default for structs can NOT be changed. default will always be uninitialized. Meaning a struct with a field like public int X = 42; will only have the 42 in there if the constructor is called. A freshly initialized array of that struct will still only contain structs with X = 0 for all elements. The same is true for the default keyword. And yes, the same is true if the default constructor of the struct assigns values like public Struct() { X = 42; } will still have X = 0 when using default. default for structs is basically all fields zeroed.
@parlor3115
@parlor3115 4 ай бұрын
I think he meant the .NET team changing the behavior of the keyword. And if you expect it to resolve to null and write your code with the assumption, but in .NET 10, it returns something else, then you'd have to make drastic changes before upgrading to the newest runtime version
@bilalakil
@bilalakil 4 ай бұрын
Note that you cannot actually write public int X = 42 in a struct. You also cannot write a default constructor.
@narumikazuchi
@narumikazuchi 4 ай бұрын
@@bilalakil Sure you can. It's been a feature of the language since C# 10.
@bilalakil
@bilalakil 4 ай бұрын
@@narumikazuchi Interesting! I'm a Unity developer, and Unity's stuck in C# 9 lol. Jealous.
@MisterFusion113
@MisterFusion113 4 ай бұрын
I came here to argue when I saw the title 😂 this is perfect
@sasukesarutobi3862
@sasukesarutobi3862 4 ай бұрын
I expect a lot of people would have chosen the original solution simply because they know that "null is bad", but don't realise they're often choosing a less obvious null, so they're hiding the problem rather than making the change they want. Returning an empty collection is a much nicer solution as it preserves the expected type. I'd also suggest either defining some error type that gets passed back and/or using task results if you do want to communicate some error information. That way, you have something explicit that you can check for rather than expecting calling code to know what sort of errors they'll need to handle.
@Max_Jacoby
@Max_Jacoby 4 ай бұрын
Somewhere I read that "default" was invented for generics when you don't know the type of T. So default could be null or 0 depending on T. If you use default outside generics then you are using it wrong.
@woocaschnowak
@woocaschnowak 4 ай бұрын
Are you actively looking for those samples, or do they appear in your feed? Cause I don't know if I have my LI feed broken (or quite the opposite ;-)) but I don't see to much programming advices, let alone "Code Cop" candidates 🙂 And yeah, returning empty collection is waaaay above returning null collection.
@MonochromeWench
@MonochromeWench 4 ай бұрын
The only time i'd ever use default is in generics. Using default on a Nullable value type seems like asking for confusion and a good reason why you shouldn't always just use it (you get null, not zeroed struct). If you mean null, use null. The difference between the behaviour between reference and value types also a good reason not to use it. Explicitly using null for refence types and new for value types seems like the less confusion option. Its a good idea to make your intent clear.
@Astral100
@Astral100 4 ай бұрын
never seen this advice. thank god
@berrigo2
@berrigo2 4 ай бұрын
I see the "Propery {get;set;} = default;" gets spit out when you use scaffolding with EF6 to generate CRUD pages. Any idea why they stick it in there?
@evancombs5159
@evancombs5159 4 ай бұрын
My guess is for primitive types that are not nullable. It is generic code so they do not necessarily know the type, and some types cannot be null.
@alonmore28
@alonmore28 4 ай бұрын
Agree with your video. Generally I don't much understand the use cases of the default keyword. Setting a default value to some variable should be relevant to my app and I shouldn't just use a keyword. For example, having a default int value for one of the properties in my class, where 0 (the default) might actually have a meaning in the context, this may cause conflicts. Also, definitely avoid returning nulls when possible. Generally speaking, if you are able to anticipate different scenarios in your code, you should have them all handled correctly. Returning null may be ambiguous with the reason null was returned, for example. When a method need to return a collection, and a valid scenario caused that there will be no results, just return an empty collection instead of null. By the way, I am not familiar with the " = null!" Syntax. What is the meaning of the exclamation point in the end?
@Denominus
@Denominus Ай бұрын
Ha, a bunch of my pet hates crammed into one code snippet: 1. Repository Pattern. 2. Returning a null IEnumerable instead of an empty one. 3. Automapper. Not that I would use default here either, but it's lower on my list of bad practices than the above.
@DisturbedNeo
@DisturbedNeo 4 ай бұрын
Also worth noting that the default value of a nullable value type is null, not the default for the underlying type. Meaning: int i = default; // 0 int? j = default; // null It does make sense, but it’s another little gotcha supporting the argument against using default.
@yakovkemer5062
@yakovkemer5062 4 ай бұрын
Depends on the case, for list - maybe it is a bad idea, but for single record it is always good to throw not found exception. IMHO.
@BigPoleTightHole
@BigPoleTightHole 4 ай бұрын
I'm admittedly a purist, and I do my best to avoid returning null If I can help it. Can't have a null-ref exception if you never return null. :)
@Noceo
@Noceo 4 ай бұрын
I am all in for reducing the use of `null`, but not at any cost. I have seen code become wildly complicated, in an attempt to avoid `null`. And while `null` is definitely sub-optimal, it's far from the worst thing you can do.
@Sayuri998
@Sayuri998 4 ай бұрын
I don't necessarily agree on not returning nullable enumerables. There is a difference between error and no results. I would return an empty enumerable if and only if there are no results. If a method can fail, I would rather return null or a OneOf. Exceptions are evil and should be avoided because they make a mess of code flow and adds tons of verbosity in my opinion, hence I prefer return types to contain the error.
@RobinHood70
@RobinHood70 4 ай бұрын
One thing that struck me as you were showing different return types is what if it's "bool" originally and you return default, but then later you change it to a tri-state return type of "bool?", like handling nullable boolean database fields, for example. Your code logic has then changed, but did you really mean it to or did you actually want to return a hard false? That depends on the code, of course, but it's something that would be easy to miss by using default. Also, junior devs might not even know whether the default would return null or false in this situation.
@billy65bob
@billy65bob 4 ай бұрын
I like default quite a bit. I mainly use it to make my generics even more generic, so I can handle both reference and value types in one class/method. I actually found it really annoying when I had to roll separate ones for each... The main other thing I use it for are for optional parameters, e.g. the CancellationToken on my async methods. That said, these examples are bad, and the person who posted them should feel bad.
@klocugh12
@klocugh12 4 ай бұрын
Null and empty are semantically different. Null = no collection Empty = an existing collection with 0 elements. Depending on intent of what you want to communicate, this is not interchangeable. E.g., it might make sense to return null instead of throwing exception if there is some issue preventing it that is not, well, exceptional.
@sacredgeometry
@sacredgeometry 4 ай бұрын
Whilst I agree its very rare that you would want null instead of an empty collection where one was meant to be returned.
@joshpatton757
@joshpatton757 4 ай бұрын
So, I think the point you make is true here, strictly speaking. But how often do you come across a situation where semantically there is no collection to return, as opposed to an empty one? I can't think of a single instance IME where that has actually come up for me. Usually the fact that we are programming 'about' a collection implies there is business rules for that collection, which means we expect a collection even if it may be empty. Unless you are talking about cases like 'we tried to query this webservice to retrieve this collection but got back an error 500'?, in which case I actually would have my client class accept a default (null) collection, but I would also have some sort of TaskResult that needs to be checked before using the collection and thus handle the possibility that we couldn't connect before the possibly null collection gets used - the service client still would not be capable of returning null.
@wobuntu
@wobuntu 4 ай бұрын
In my opinion returning null on a method which returns an IEnumerable should be marked as a warning by default in all IDEs. We even forbid that in our team and it prevents you from lots of unnecessary bugs and keeps the caller code more concise
@isnotnull
@isnotnull 4 ай бұрын
public string FirstName {get;set} = default! What do you prefer instead? I usually assign an empty string to avoid null reference warnings
@Astral100
@Astral100 4 ай бұрын
I turn off null checker and live a happy life
@zbaktube
@zbaktube 4 ай бұрын
If a developer cannot decide whether to return null or default, that developer should throw an exception 🙂 I prefer return things that lessens the possibility of a bug. In this case of the enumerator, I would go for the empty one. But in general I would ask around about railway oriented programming among teammates...
@IssaFram
@IssaFram Ай бұрын
5:08 is the important part of this video
@MaximilienNoal
@MaximilienNoal 4 ай бұрын
Default means null for reference types, lol.
@berry212
@berry212 4 ай бұрын
Null IS the default
@djp_video
@djp_video 4 ай бұрын
This is the same reason I stopped using the 'var' keyword in most situation -- you can't tell at a glance what the code is doing. Makes debugging so much harder! I hate having to decipher someone else's code when it's littered with 'default' and 'var' and other keywords that make the data types ambiguous. But you and I disagree on one thing... I do return nulls in some (not all) of my methods to indicate an error condition instead of creating and throwing an exception. Exceptions are overused in my opinion. Not just because of the performance hit, but try...catch blocks messy up the calling code more-so than a quick null check. Exceptions are appropriate in many situations, but just to indicate that required data is unavailable isn't usually one of them. Using nulls is standard practice in my code, so I already check for it anyway, and the null coalescing operators make it much easier to do.
@Athurito
@Athurito 4 ай бұрын
1 min into the video i am like why should i return null or default instead of an Enumerable.Empty and if he uses EF core he always has a reference and the list cannot be null
@MarkCastle
@MarkCastle 4 ай бұрын
What about passing optional Params eg , CancellationToken cancellationToken = default
@StrangerOks
@StrangerOks 4 ай бұрын
Strange that the memory allocation issue is almost not discussed here in case of returning of Empty Array(or List). Taking into account that this code is returning object collection with potentially big amounts of fields. In general for me, the usage of "default" is suspicious, because each time I would like to check what is returned. And that takes unneeded additional time. About the null, if you call a method that returns reference type I would always expect to check the null in the result. From other side, if I make such a method - all the behavior and returned edge cases should be described in the annotation. Including Exceptions, Nulls, Empty or unknown results. With nullable type support in the latest C# this becomes easier, but I would still like to see good annotation explaining what case is actually cause returning of null.
@AlFasGD
@AlFasGD 4 ай бұрын
In C# 12 you should be able to use [] instead of the long empty enumerable expression, though I didn't see Rider recommending this
@gamedev_expert
@gamedev_expert 4 ай бұрын
upgrade rider version
@user-nh5fg4se5w
@user-nh5fg4se5w 4 ай бұрын
Can you provide me a good resouce to learn microsoft SQL?
@iamnietzsche7334
@iamnietzsche7334 4 ай бұрын
Imo, if the method has a nullable return type, it's just a clear contract, you either get something or null. Ideally I'd want an Option type in C# like some other languages do, in that way it's more enforced.
@evancombs5159
@evancombs5159 4 ай бұрын
I see little difference between Nullable and Option?
@mattfbk
@mattfbk 4 ай бұрын
In my latest project I gave the concept of ResultT and OptionT a try and liked it so far 😊 to be honest I'm not even sure what that null was supposed to mean in this example 😅
@Ext3rmin4tor
@Ext3rmin4tor 4 ай бұрын
The Option data type is certainly the best choice as the type checker will ensure that anyone MUST handle having or not the value, and it's the only type safe way of handling values that may or may not exist. You can even overload the linq syntax to have a declarative way of composing operation involving optional values without the need of explicitly handling the existence check at every step.
@F1nalspace
@F1nalspace 4 ай бұрын
The only thing i ever use default for is in generics, everything else uses an explicit type.
@fifty-plus
@fifty-plus 4 ай бұрын
If people are using the keyword they should know its intent and the value it would imply. I don't see that people not knowing as a good argument, that's just a lazy programmer not knowing their craft. A better argument is to know when to use default and, in this case, not use null in the first place or if you have too for some unknown reason, use it properly knowing what it does. I like this series, Nick, it makes people aware of all the terrible advice that gets upvoted and hopefully triggers something in them to learn their craft more thoroughly and avoid using a search engine or LLM as their first reference point.
@SG_01
@SG_01 4 ай бұрын
There is also the difference between returning default and a new struct. Returning default may in fact return an invalid struct, which is not at all clear
@rik0904
@rik0904 4 ай бұрын
good topic. for me default is not great thing, Im not sure but I thing that there are null for custom struct to, so here the logic of it is broken. I try to not use null in my code, but sometimes it is a best way. I remember in past there was this talk about, don't return null, return object even if it is empty, but this approach can be even worst, it is fine for collection, but for object you just get a mess. I thing programmers should have only one rules, 'every rule is suggestion'. There will be always some edge case where rule will make program worse
@Esgarpen
@Esgarpen 4 ай бұрын
I will die on the "Don't return null in any way shape or form - ever" hill.
@Astral100
@Astral100 4 ай бұрын
And as you can see by the likes, you will die there alone.
@garcipat
@garcipat 4 ай бұрын
This can also be dangerous. Use null if you want to bw explicit. It is should be treated as a valid value, not just as not assigned.
@Silentsouls
@Silentsouls 4 ай бұрын
If you promisse an IEnumerable, then it should not be null. For when it gets used in linq queries, you do not want an exception for returning null. default has its place, just like with everything in C#, not always everywhere.
@michael40card
@michael40card 4 ай бұрын
Yay, Enumerable.Empty for the win! I completely agree with all of this! Niggle: why return e.empty within an .Any if check at all if the EF result is already an empty collection 😅
@DiomedesDominguez
@DiomedesDominguez 4 ай бұрын
I mustly return null or a Not Found implementation.
@haxi52
@haxi52 4 ай бұрын
I don't really agree, no problem with returning `default` vs `null`, it's a similar argument to `var` vs `type`. But I think you should emphasize avoid returning null, regardless of return type, IEnumerable or otherwise.
@shumito
@shumito 4 ай бұрын
essentially is the same reason why I hate "var" . I prefer being explicit
@knixa
@knixa 4 ай бұрын
only place I ever really feel okay with default is when there are optional CancellationTokens being passed in
@andersborum9267
@andersborum9267 4 ай бұрын
I have to disagree on this one; as you said, default is just syntactical sugar (i.e. this discussion is entirely about readability), and if you're writing functions that doesn't fit the screen (which you shouldn't), it's all comes down to habit and preference. I can obviously read both types of implementation but find that the default keyword comes across as a bit more expressive. As for returning null (or default) for methods signatures returning enumerables or iterators, just don't - again, agree entirely on this one; however, would use the ternary operator in the return statement.
@sanetby
@sanetby 4 ай бұрын
agree, returning null is a bad practice indeed, but default is not a cure, you're just hiding the problem deeper and a hidden problem is much worse than an obvious one
@TheWarTurkey
@TheWarTurkey 4 ай бұрын
I guess it depends on your codebase. In my case, I add and remove types from my codebase and swap between `class` and `struct` all the time, so `default` works best for me.
@fifty-plus
@fifty-plus 4 ай бұрын
That's potentially, without knowing your codebase, a good reason not to use default. It can drastically, unintentionally change meaning under refactor and introduce numerous subtle bugs.
@TheWarTurkey
@TheWarTurkey 4 ай бұрын
@@fifty-plus That makes sense, but I haven't had an issue with my code base.
@austin.valentine
@austin.valentine 2 ай бұрын
Nick is right. That’s garbage. Also, how do you different an absent value vs an existing value that matches default value for that value type?
@charclay
@charclay 4 ай бұрын
Why not return new()?
@evancombs5159
@evancombs5159 4 ай бұрын
To me the default keyword is a half-baked keyword. Default is a keyword that should be used to help us generate more robust code in a cleaner way. Instead we just have this confusing keyword that looks better than using null, but the reality is in the majority of cases it is just another null. Null should not be the default value of a class. Default should be a class state that we can define and check against. For backwards compatibility reasons, null should only be the fallback state if no default state has been defined.
@margosdesarian
@margosdesarian 4 ай бұрын
Wow i never knew there was such a thing as Enumerable.Empty ... thanks Nick
@birdasaurusrex
@birdasaurusrex 4 ай бұрын
Default is a good abstraction for generics. However, in general, I don't like using it. :)
@schk3
@schk3 4 ай бұрын
5:12 "Don't return null"
@JohanNordberg
@JohanNordberg 4 ай бұрын
I think I've only used "default" as a default value of an argument / prop. Avoid being fancy at all cost.
@brianparker4858
@brianparker4858 4 ай бұрын
Meh! I started using null then ran into problems using null with generics, I then switched to default(T) the lazy programmer in me doesn't think about using both... I think with practice and exposure of its usage its much like "var" usage. If the type is obvious, it's fine to use. Its an interesting argument it doesn't tell you the type... "null" doesn't either...
@obinnaokafor6252
@obinnaokafor6252 4 ай бұрын
I hope you credit the author of the code snippets?
@MrJacquers
@MrJacquers 4 ай бұрын
And we learned Nick has a very narrow FOV :P
@unexpectedkAs
@unexpectedkAs 4 ай бұрын
Some methods can be long by the way.
@nevett
@nevett 4 ай бұрын
99% of the time the absence of a result from a get method should be an error. If you can provide a cheap way to check for likely success before executing a get method, then do it e.g. and Exists() method. If you can't, then include a success status code in the response. I wouldn't say "never return Null" as it has its place in high performance systems, but it should generally be avoided.
@lextr3110
@lextr3110 3 ай бұрын
if your return type return a nullable.. what is the problem? the caller know it could return null.. so you check for null first when using the result..
"Don't Use Loops, They Are Slow! Do This Instead" | Code Cop #011
9:51
The Right Way to Check for Null in C#
9:35
Nick Chapsas
Рет қаралды 94 М.
UFC 302 : Махачев VS Порье
02:54
Setanta Sports UFC
Рет қаралды 1,4 МЛН
TRY NOT TO LAUGH 😂
00:56
Feinxy
Рет қаралды 10 МЛН
Универ. 13 лет спустя - ВСЕ СЕРИИ ПОДРЯД
9:07:11
Комедии 2023
Рет қаралды 3,7 МЛН
What is Span in C# and why you should be using it
15:15
Nick Chapsas
Рет қаралды 248 М.
"The readonly Keyword Is Useless!" | Code Cop #012
9:42
Nick Chapsas
Рет қаралды 35 М.
RECORD TYPES | Exploring C# and DOTNET | Rahul Nath
15:32
Rahul Nath
Рет қаралды 2,4 М.
Manage Nulls Like a Boss and Never Fail!
21:43
Zoran Horvat
Рет қаралды 10 М.
Don't throw exceptions in C#. Do this instead
18:13
Nick Chapsas
Рет қаралды 249 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
Why Do C# Developers Hate The var Keyword?
11:15
Nick Chapsas
Рет қаралды 60 М.
What are record types in C# and how they ACTUALLY work
15:36
Nick Chapsas
Рет қаралды 117 М.
"Stop Using Singletons in .NET!" | Code Cop #009
13:52
Nick Chapsas
Рет қаралды 75 М.
UFC 302 : Махачев VS Порье
02:54
Setanta Sports UFC
Рет қаралды 1,4 МЛН