The Right Way to Check for Null in C#

  Рет қаралды 94,116

Nick Chapsas

Nick Chapsas

Жыл бұрын

Check out my courses: dometrain.com
Become a Patreon and get source code access: / nickchapsas
Hello, everybody, I'm Nick, and in this video, we will take a look at the right way to check for null in C#. C# has been around for a long time and the process of checking for null has evolved as the language itself has evolved.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasGitHub
Follow me on Twitter: bit.ly/ChapsasTwitter
Connect on LinkedIn: bit.ly/ChapsasLinkedIn
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер: 298
@nickchapsas
@nickchapsas Жыл бұрын
And for those wondering, both null-coalescing operators (??= and ??) and the ?. operator will be compiled to the "is null" version if the compiler detects that the operator is overloaded
@sealsharp
@sealsharp Жыл бұрын
That's why the Unity code analyzer complains about using null-coalescing operators.
@tottiinfo
@tottiinfo 5 ай бұрын
Why not doing this: if(!(user is object)) : this the more secure way to check for null references even if the == operator is overreriting
@T33K3SS3LCH3N
@T33K3SS3LCH3N 11 ай бұрын
Let's be real, if the == operator is overriden in such a way that it can no longer check for null then the correct response is not to adjust your coding style, but to crucify the person wrote the override.
@ficolas2
@ficolas2 11 ай бұрын
this
@Smakenzi
@Smakenzi 10 ай бұрын
agree, it reminds me of colleagues arguing back in 2014, that having IEnumerable/IReadOnlyCollection return type is not enough and you should always iterate-yield the whole collection or .ToList() clone it before returning, since the consumer of your interface can downcast the returned reference back to the original List/array and then modify the original instance.. I think we should not upfront-compensate for hypothetical retard-alert situations, or use them as reasoning. Still, the "is null" syntax looks quite neat
@ficolas2
@ficolas2 10 ай бұрын
@@Smakenzi lmao well you can also use reflection to access private methods in java for example. Your job is to prevent the users from shooting themselves in the foot accidentally, not from shooting themselves in the foot on purpose. Cloning an interface everything you return it is wild, you should not do that.
@idk-jb7lx
@idk-jb7lx 10 ай бұрын
lmao this honestly
@miserium6020
@miserium6020 10 ай бұрын
Seriously, this video was completely pointless. Content for the sake of creating content.
@TkrZ
@TkrZ Жыл бұрын
I've been using the "is null" for a while now purely because I think the syntax looks better and more readable (when you read the code in your head you're essentially translating "user == null" to "user is null" anyway), the fact you can't ever face issues with the equality operators being overridden is a nice bonus though
@vivekkaushik9508
@vivekkaushik9508 Жыл бұрын
Awesome.
@PhilipDanielHayton
@PhilipDanielHayton Жыл бұрын
This 👆
@LCTesla
@LCTesla Жыл бұрын
I hate how similar it looks to the type checking "is".
@Innengelaender
@Innengelaender 11 ай бұрын
Same for me, but is a bit annoying that Copilot still often suggests '== null' and I have to change it manually
@stevenbey
@stevenbey Жыл бұрын
I'm not going to lose any sleep over my code having `== null`. In over twenty years of programming, I've never seen the `==` operator overridden.
@JohnAndrews_nz
@JohnAndrews_nz Жыл бұрын
^^^ this
@qj0n
@qj0n Жыл бұрын
More importantly, if anyone overload it and decided that particular value is equal to null then I guess we should treat it as null
@RobinHood70
@RobinHood70 Жыл бұрын
I've seen several overrides to == and done them myself, particularly for implementing value equality on DB record key fields, but I've never once seen null overridden to have any meaning other than the expected meaning. Still, I'm slowly converting all my == null checks just to be sure that when I want to be sure I'm doing a ref check that that's what I'm actually getting.
@stevenbey
@stevenbey Жыл бұрын
@@RobinHood70 obviously my experience doesn't apply to everyone but, having contracted at almost 20 companies, I'd say my experience isn't unusual.
@RobinHood70
@RobinHood70 Жыл бұрын
@@stevenbey I didn't mean to imply that it was, just that overriding equals does happen. It obviously depends on what kind of work you do. I used to do a lot of database work, so value equality was a pretty common thing for me to write.
@soverain
@soverain Жыл бұрын
Unity dev here. I like that you mentioned the operator overloading in Unity, but it’s applicable only on object derived from UnityEngine.Object. On everything else and all your standard managed objects, you’re good to go with the « is » and « is not » operators. Good video though!
@countycowpoke
@countycowpoke Жыл бұрын
What I like most about your videos Nick, is that you explain the "why" behind it and I often learn just as much by the behind the scenes things as I do the intended topic. For instance, a while ago I picked up on your video about overloading default methods like !=, == etc. Thanks for all your videos!
@ExpensivePizza
@ExpensivePizza Жыл бұрын
I've never bought into the idea that we need to guard against someone overloading the == operator incorrectly. Don't get me wrong.. the "is null" operator is fine but the idea that you would ever need to assume an operator overload is implemented to do the opposite of its intention is just insane. We don't go around calling the `Add` method expecting it to subtract. Nor should we expect == to not equal.
@nickchapsas
@nickchapsas Жыл бұрын
I get you but It's actually deeper than that. Consider you are using NRTs in your own code and you define a type as nullable. What do you really when to check when you write "== null"? I would be very surprised if what you intend to do is check the reference of the type being null. But if you won't use "is null" and there is an overloaded operator then you are at the mercy of said operator, which can be dangerous. That's what "is null" saves you from,
@FrostedCreations
@FrostedCreations Жыл бұрын
@@nickchapsas I don't normally disagree with but this time I really do. You can't (or rather shouldn't) just assume that code written by someone else is wrong. If someone is crazy enough to overload the == operator to change how nulls are compared they're doing that for a reason. Whenever you work in a team you're "at the mercy" of other people's code. Also personally I hate the syntax of "something is null", it's too wordy for me and looks too much like Visual Basic.
@ExpensivePizza
@ExpensivePizza Жыл бұрын
​@@nickchapsas I've been coding for 30 years... about 20 of them in C# so maybe I've just got a good understanding of how things work. That said, I also work on teams with less experienced coders and I just don't see this as being a real source of actual bugs. Most of the time when this topic comes up it only exists in contrived examples (much like the one in your video). I must admit the "is null" syntax looks better but at the same time it's another rule to learn. There's decades of code out there using == operators for null checks so at the very least new coders still need to understand both for quite some time. More importantly, there's now a new source of bugs when refactoring old legacy == operators to "is null" checks because it's possible to break the original intention of the code if operator overloads where actually used to solve a real world problem. "is null" might very well be objectively better in many ways. I'm just playing devil's advocate and pointing out that there's always a trade off.
@mrahhal
@mrahhal Жыл бұрын
Fully agree. It's crazy to me how this has been so easily accepted as the "default" now. My team tried to introduce it to our codebase but I flat out rejected it and suggested we should keep on using the usual operators. The only place this might make sense is when you actually need it for chaining pattern matching. Also, "is" and "is not" are not more readable to me. They're also not symmetric, unlike "==" and "!=".
@lupf5689
@lupf5689 11 ай бұрын
We prepared a gallows in the company backyard for developers overloading standard operators. It's considered an important part of our effort to enforce the coding guidelines.
@diadetediotedio6918
@diadetediotedio6918 Жыл бұрын
I pretty much like 'is' and 'is not', it is pretty readable.
@stefano_schmidt
@stefano_schmidt Жыл бұрын
Python style
@rodrigo6459
@rodrigo6459 Жыл бұрын
I do the same… that ==, != I just hate it!
@patfre
@patfre Жыл бұрын
I much prefer it which I why I always use it to check for null it’s easier to read and it avoids unwanted operator overloads from messing up the check
@UweKeim
@UweKeim Жыл бұрын
@@stefano_schmidt SQL style
@StevDevOfficial
@StevDevOfficial 2 ай бұрын
​@@UweKeimyeah its more like SQL
@mohamedh.guelleh630
@mohamedh.guelleh630 Жыл бұрын
That's also how SQL server queries check for null values. So it is actually convenient to use the same syntax null check in server back-end and in database.
@peledzohar
@peledzohar 10 ай бұрын
Great feature and a great video. In fact I've actually written about "x is object" back in 2019 in a blog post I've named "The perfect non-null test". In c# 9 when they've added the not keyword it got that much better with "x is not null" - but still learned something new about how it actually works in lower c#, so thanks!
@JosifovGjorgi
@JosifovGjorgi 11 ай бұрын
Things I learn from this video: 1. Operator overloading is really good in theory, but very bad in practice 2. C# is very complicated language, a simple thing like null check can be done in 10 different ways.
@tropictiger2387
@tropictiger2387 Жыл бұрын
If you find someone overwriting == the correct course of action is not to go along with what they are doing but instead to beat some sense into them. Overwriting == shouldn't be done lightly and if you must do it it should not impact existing code.
@xlerb2286
@xlerb2286 11 ай бұрын
For a first offense you should use a rod no bigger in diameter than your thumb. For a second offense feel free to introduce them to your grandpappy's walking stick, "old hickory". Third offenses aren't an issue. Kidding aside I agree, it's rare that operator overloading is actually needed and as it's hidden logic you can't see by looking at the code it often just leads to late night debugging sessions. So use with great care and only if you have a legit need. In 30 years of C++ / C# coding I don't remember ever having a need.
@shaicohen2
@shaicohen2 11 ай бұрын
totally agree, I'd raise hell if I saw that in a PR. that being said, how do you control/prevent overwriting == in nuget packages?
@tropictiger2387
@tropictiger2387 11 ай бұрын
@@shaicohen2 Luckily you can't override == for primitive types and overloaded operators are limited to the type they are defined on. This means that if == is overloaded in a nuget package it would only affect types defined in that package. The only way I can think of that operator overloads, in a nuget package, could cause harm is, if you had a nuget package installed and you upgrade to a new version where the == operator has been overloaded in a way that is different from what it was before.
@jshanker2005
@jshanker2005 11 ай бұрын
I have been coding for over 30 years and as a matter of principle, I never allow overloading of basic operators within the teams I work in.
@Nerdsown
@Nerdsown 11 ай бұрын
I often override Equals for new immutable classes and structs. If I override equals, then I always override == so it works the same way. Not doing so would be a trap.
@antonbergstrom6740
@antonbergstrom6740 Жыл бұрын
Personally, I enjoy using the maybe/option monad. It keeps my code clean from null checks, ensures that the caller handles both scenarios of when there is and isn't a result and it can handle any type, not relying on nullable being implemented.
@notoriouslycuriouswombat
@notoriouslycuriouswombat Жыл бұрын
i like the new features, thanks for bringing them to our attention in a easily digestible way
@GufNZ
@GufNZ Жыл бұрын
I use the R#/Rider setting under code inspections to Colour Identifiers, which adds a bunch of semantic options for how to colour the code, which includes being able to chose different colours for normal operators vs overloaded operators.
@the-niker
@the-niker Жыл бұрын
This is a cool idea, that should be on by default. JetBrains take notes! That said I have never seen == to be a source of a bug, nobody is crazy enough to change the null check behavior unless it's absolutely necessary. Unlike implicit operators that can create super unintuitive ambiguity problems.
@GufNZ
@GufNZ Жыл бұрын
@@the-niker note that R#/Rider's inline type hints show an indicator wherever there is an implicit operator in use. I set them to toggle on hold of ctrl, and show/hide on double press of ctrl, so I can easily control when I see them.
@roelbrook7559
@roelbrook7559 Жыл бұрын
I like the "is null" because it's the same way you do it in SQL. And everyone knows SQL is the best programming language of all time
@zORg_alex
@zORg_alex 10 ай бұрын
Can we please start hating this guy for such statement?
@taemyr
@taemyr 4 ай бұрын
In SQL i check for Null by Not (a=a)
@TheKoneko1312
@TheKoneko1312 Жыл бұрын
I love this and I didn't knew about the weird "is not null". I wish C# would get the balls to say "okay, this will have breaking changes, we're removing all the useless stuff now" at least once a decade.
@kuroilight1676
@kuroilight1676 Жыл бұрын
Because now the == operator is now “useless stuff”, makes total sense
@mindstyler
@mindstyler Жыл бұрын
Yes. the language design team is actually working on something akin to rust editions now
@weedick1682
@weedick1682 Жыл бұрын
if == operator is overwritten and does not handle (x == null) case then it's either a bug or intended behavior
@nickchapsas
@nickchapsas Жыл бұрын
Ha, but that's actually the responsibility of the underlying type, not yours. If you're using NRTs for example and something is nullable because you defined it as such, then == automatically implies a reference check. That's why "is" is what you would want to use in this situation.
@nikolazagorac8634
@nikolazagorac8634 11 ай бұрын
Wow! I didn't have a clue about his... Thank you!
@nove1398
@nove1398 Жыл бұрын
Never thought about it this deeply actually. Good perspective check for me.
@mitar1283
@mitar1283 11 ай бұрын
I actually use "==" and "!=" for simple null checks its just personal preference because I like to keep the "is", "is nor" "or" and "and" stuff exklusive for more complex pattern matching since that is the area it acutally helps with readability
@nthonymiller
@nthonymiller 11 ай бұрын
Thanks for the vid, it's been a burning question for me lately which way is best.
@eugenevv
@eugenevv 11 ай бұрын
Thanks, Nick! 👍
@Schnickalodeon
@Schnickalodeon 11 ай бұрын
As always an fantastic video! Could you do a video where you explain the different steps how C# code will be compile: Lowered, IL ... etc.? That would be awesome!
@victorsorokovikov
@victorsorokovikov 11 ай бұрын
Thanks for pattern matching examples.
@Moosa_Says
@Moosa_Says 11 ай бұрын
Ive been using all these features not because I knew about it but because Resharper always suggested me to change my conditions according to these new ways an di kinda loved it :D
@retrodad9390
@retrodad9390 Жыл бұрын
that's why I use the option. type like int the rust language, It's easy to create . Like the option type in rust.. I also use option because not everyone in a team thinks about this when under pressure... Thanks for the video!
@TraceBandit17
@TraceBandit17 11 ай бұрын
I will overload equality operators when I'm not necessarily wanting to resolve whether the reference is the same but rather based on property values, like an object with a DateTime field. I will overload so that the objects are checked for null (via 'is') first then whether the DT field is the same. If they are, the objects are "equal". I do the same for objects that have an ID field as two objects cannot have the same ID without being equal.
@200KGHantel
@200KGHantel Жыл бұрын
Thanks for the vid, I'm still unsure tho, is checking with '?' the same as 'is null' ?
@AltairWhispers
@AltairWhispers Жыл бұрын
By using railway or functional programming, you shouldn't worry about null values as long as you are consistent with your conventions, for e.g. using the following records Result.Success(T value) and Result.Failure(IFailure failure) with a boolean property called IsSuccess. It tends to be more business oriented, rather than dealing with framework sugar syntax.
@mehdizeynalov1062
@mehdizeynalov1062 Жыл бұрын
@Nick - thanks for the video. can you overload object's null check (== null ) operator? also how does it impact ?? null coalescing operator?
@youraveragedude8767
@youraveragedude8767 Жыл бұрын
It doesn’t work then! Null-coalescing operator literally doesn’t work in Unity and that’s one of the reasons why I hate it! Only if the is operators could theoretically also be overloaded 😢
@Landoseixas
@Landoseixas Жыл бұрын
Hi, Nick, thanks for the great advice. Is performance affected by this method ?
@nickchapsas
@nickchapsas Жыл бұрын
Not anymore. It's used to be
@Sahuagin
@Sahuagin 10 ай бұрын
I use a naming convention of a "maybe" prefix for my nullable variables. I then use the form: if (maybeValue is not { } value), which usually then is the exceptional case (return an error message or something), and then the normal case can continue on with the known non-null value variable.
@maxsamarin9002
@maxsamarin9002 Жыл бұрын
Thanks for the video! I'm a bit confused about the Unity part - which classes exactly have overridden the == operator? Some Unity's own classes? If I'm using only my own classes in Unity, using "is null" should be safe, right?
@marcusotter
@marcusotter Жыл бұрын
Yes, you can use pattern matching and "is null" for your own classes as long as they do not inherit from any Unity class (MonoBehavior, ScriptableObject, etc). In Unity, checking for null (with ==) does not check if the C# reference is null, it checks if the Object has been destroyed in the scene. So if you do if player == null you are checking if the player object exists in the scene, but with if player is null you check if the C# reference is null, which is not very helpful as it usually is almost never null. In 99% of cases you want to use == null in Unity.
@maxsamarin9002
@maxsamarin9002 Жыл бұрын
@@marcusotter Thanks! Looks like I wasn't so reliant on Unity's own shenanigans in scenarios like in your example. If I want to check if a reference is null, I literally always means to check whether the reference points to a null object or not. For checking whether a gameobject has been destroyed I would Destroy() the object and in addition set all references to it as null (like in the player example In these cases I like to create a layer of abstraction). In this case, sounds like using "is null" should be safe for be both for my own and Unity's classes, as long as checking for null reference is literally what I'm after.
@proosee
@proosee 10 ай бұрын
TBH I haven't seen operator override for years now - it's really exotic tool that can be used only in domain objects and you have to have really good reason to override it, where most null checks are performed od DTOs in layers above.
@rodrigodearcayne
@rodrigodearcayne 11 ай бұрын
I always use == and != because of a habit and I never overload equality operators nowadays, let alone null equality. Personally I think that being allowed to modify what == means in such a hidden way was a design mistake. It looks cool until it bites you. A much better option IMHO is to generate (with Resharper) or implement by hand some EqualityComparer for your classes and give them a meaningful name. Like IdComparer or ValueComparer for example. So you get the special behavior only when you need it and that’s clear to everybody reading your code. No surprises. Then ok: is/is not looks better 😅 BTW, great channel Nick!
@imaginative-monkey
@imaginative-monkey 11 ай бұрын
Recursive pattern, used in 'is {}', is only available from C# 8. Since it's syntactical sugar, you can change the language version in your csproj file without changing the .NET version with `8.0`. This worked for my .NET Standards 2 project
@urbanelemental3308
@urbanelemental3308 Жыл бұрын
Been using "is" and "is not" for some time now. I like how readable they are.
@MarkRidgwell
@MarkRidgwell Жыл бұрын
I've been using the CSharpIsNullAnalyzer analyzer in my code for a while to pick up cases where I've not used the `is null` pattern match - was using ReferenceEquals before in a few places to be explicit about what comparison I wanted, but hated how that looked when reading the code
@olegvorkunov5400
@olegvorkunov5400 11 ай бұрын
Learn something new from this video. Also, my policy is to never use operator overload and in most companies I worked for operator overload is prohibited.
@MrSurfsAlot
@MrSurfsAlot Жыл бұрын
At 2 minutes in why is Rider highlighting the 'if' ? I just started using rider on my macbook and am confused why I get so many squiggly's and warnings for stuff I don't in visual studio
@phirus646
@phirus646 Жыл бұрын
I'll just bookmark this video for my next code review
@Looooooka
@Looooooka Жыл бұрын
What about default? isn't that the new way of checking reference types?
@lylobean
@lylobean Жыл бұрын
What is the cost time wise difference between '==' or 'is' with the (object) casting?
@curtis6919
@curtis6919 Жыл бұрын
Nothing. All methods produce the same JIT.
@stuartdotnet
@stuartdotnet Жыл бұрын
I laughed when you mentioned VB...when I was working with NULLs in VB way back I saw many different ways of writing it, the best being: If Not item Is Nothing
@ChrisUG
@ChrisUG 8 ай бұрын
Anyone complaining about the verbosity of "is not null" is probably doing something strange anyway. When do you WANT something to be null? The normal way to code defensively is to do a null check warn, tidy and drop out if its null. You can do that with "if (x is null) return;" and the rest is implicitly not null and you save on indentation and compliexity.
@garcipat
@garcipat Жыл бұрын
You should formulate if statements positive for no double negation.
@rostyslavskarbek3190
@rostyslavskarbek3190 10 ай бұрын
I tried if (user.Child.Name is not null) when user is null and it throws System.NullReferenceException. It looks like it does not translate into if (user?.Child?.Name is not null)
@creeperlv6668
@creeperlv6668 Жыл бұрын
2:40 The pain of using Unity3D's ages old C# is REAL. It seems that C# in Unity3D was trapped in a time cage that only move forward in a REALLY slow speed. It's kinda like Java 8 :-(
@soverain
@soverain 11 ай бұрын
Well, we are at C# 9 right now, which adds a lot. We are missing some conveniences from C# 10 like file scoped namespaces but I think C# 11 is not as big of a change as the previous versions.
@billy65bob
@billy65bob Жыл бұрын
I'm quite a fan of `switch(param) {case null: ... case TypeA a: ... case TypeB b: ... }` Also, what is it with `if(param is var a) { ... }` and `if(param is { } a) { ... }` having different behaviour? if you're not aware, the former accepts nulls, but only if you don't put param's actual type in there. But geez... Overloading static operators like that is insane... why would you even do that? I'm quite happy to stick primarily to `==` and `!=`, but then I've also not worked on any code that overloaded static operators, not even to just forward them to Equals() and CompareTo(). Even with the IEqualityOperators and IComparisonOperators interfaces in .NET 7 (if we ever more on), I don't see that changing... 2:25 if you want the technical reason, the Equals function is non-static, and with the variable being a null, the runtime cannot access the vtable (this is where the NRE occurred) to find the correct Equals function.
@andersborum9267
@andersborum9267 Жыл бұрын
Agree, "is null" both reads much better and is the better option from an implementation point of view.
@fabianmitchell9443
@fabianmitchell9443 Жыл бұрын
"is null" reminds me of all the tsql i used to have to write. i also remember using IsNothing() in VB back in the day. switching to "is null" in c# is going to be difficult. it just feels foreign to c# to me
@sagielevy
@sagielevy 11 ай бұрын
I noticed that in Unity doing `gameObject == null` might also be wrong when trying to check if a game object has been destroyed. I read that the check should be `gameObject == null && gameObject.Equals(null)`. Is this correct and if so what's the difference in the overloading for null vs Equals?
@manofapocalypse
@manofapocalypse 5 ай бұрын
in unity "== null" means marked for destroy by engine so its not yet null GameObject == null , will return true but Object == null , will return false u can use this method to check if its really null or not public static T OrNull(this T obj) where T : Object => obj ? obj : null;
@sagielevy
@sagielevy 5 ай бұрын
very nice, thanks I'll try it@@manofapocalypse
@yeica
@yeica Жыл бұрын
I didn't know about that null check with pattern matching
@jacobstamm
@jacobstamm Жыл бұрын
Anyone who tries to overload the == operator in my code base has to walk the plank
@petehd3833
@petehd3833 Жыл бұрын
With if(null == item) you will also get everytime the right null check. Because you can't override the == of null. The operater == will always take the left sight oft the operator to check the equal.
@nickchapsas
@nickchapsas Жыл бұрын
As you can see in the video, you can totally override it
@gumpyoz
@gumpyoz Жыл бұрын
What are your thoughts on using "is object" when doing null checks?
@nickchapsas
@nickchapsas Жыл бұрын
It's the same as "is {}". I think that both of them don't clearly show intent (that it is a null check) to the reader.
@jnyrup
@jnyrup Жыл бұрын
A benefit of 'is not null' is that it emits a compile error if you try to null check a value type. 'is object' only emits 'this is always true'.
@drewkillion2812
@drewkillion2812 Жыл бұрын
I'm fine using is null. But what kind of maniac would override the equals operator to have the null check return another value. In all my years I have never had any one on my team or came across any NuGet packages that did this.
@JohnAndrews_nz
@JohnAndrews_nz Жыл бұрын
Eh.... yes you can override the == operator and !=.... but really how often do you do that? Sure a 3rd party library may do it and hide it from you.... but really? I'm sure this would be needed in some places or some use cases. But for the majority, eh ill keep using == and have zeros problems like i've been doing for 20 years in c#.
@brianviktor8212
@brianviktor8212 Жыл бұрын
Even if you overload the equals operators/methods, you have to ensure the outcome is externally identical to all other equality checks. For example you have to ensure that "yourClass == null" is false if an instance exists, otherwise true, even if both sides are null. ReferenceEquals is useful for the part where you implement the equality check internally, as to ensure you don't just use your own equality methods reciprocally. Also because you *can* overload the equality operator, it means it is preferable to use "==" because it is properly doing the equality check logic. It is overloaded BECAUSE other means are lackluster.
@darknessgp1
@darknessgp1 Жыл бұрын
I don't like his thought of "someone could have overloaded it poorly". Well, yea, null check might not work right. Hell, lots of code might not work right if someone wrote poor code that you are making your code dependent on.
@brianviktor8212
@brianviktor8212 Жыл бұрын
@@darknessgp1 Exactly. Poorly written code can be a menace in many ways, and can ruin all sorts of conventions and reasonable expectations.
@niteshsetin
@niteshsetin Жыл бұрын
So i am not doing any operator overloading and also not using unity. Does object==null still valid? Are we just looking some special case here?
@nickchapsas
@nickchapsas Жыл бұрын
You might not be doing any overloading but do you own every single type you are using? I'm suspecting not
@niteshsetin
@niteshsetin Жыл бұрын
@@nickchapsas hmm, after thinking sometime, yes i agree with your thought 👍🏻. One question, does this 'is null' work for a observable collection , List as well?
@ManInTheFridge
@ManInTheFridge Жыл бұрын
This is a pretty elegant solution, but could you also have a convention where your object(s) are always returned in a list so you could just check the length? Kinda like ol' jQuery lol
@barionlp
@barionlp Жыл бұрын
is null does not work with Unity objects when they have been destroyed
@ahmadalsader1047
@ahmadalsader1047 11 ай бұрын
@nickchapsas I have checked the below var x = new Test(); x = null; if (x.Email is null ) { return BadRequest(); } and this throw an exception becuase x is null and if its converted to (x?.Email is null) should not throw an exception . while the below didnot throw exception : if (x is { Email: null }) { return BadRequest(); }
@StarfoxHUN
@StarfoxHUN Жыл бұрын
My favorite way is If(user is User notNullUser) { //Use notNullUser } I really like this approach, because i think its the safest(i think it should be safe even in a multithread enviroment but not sure about it), but also great in the case of the last example, when you need a Child of the class. So if you want to use user.Name.FullName, in this case you can do If(user?.Name?.FullName is string userFullName) { //Use UserFullName variable //instead of repetitively //user.Name.FullName }
@ConductiveFoam
@ConductiveFoam Жыл бұрын
Yeah, pattern matching like that is phenomenally ergonomic, I love it
@billy65bob
@billy65bob Жыл бұрын
I once tried to do exactly that the lazy way by writing: `If(user is var notNullUser) { ... }`. But for some reason using 'var' makes the test always pass, even with null... 🥴 At least that experience taught me about `if(user is {} notNullUser) { ... }`.
@StarfoxHUN
@StarfoxHUN Жыл бұрын
​@@billy65bobHmm using {} instead of direct type sounds interesting did not know its possible, thanks, but still i prefer to write out the type everywhere its not obvious as it helps later on when i read the code, easier to see what's going on when the type is directly visible. Also i wonder how 'var' is handed might check it out...
@nicholastheninth
@nicholastheninth Жыл бұрын
A little extra feature is that null can be used to check for null pointers as well. It took me months to figure out that I can just use ‘ptr == null’ instead of ‘ptr == (T*)IntPtr.Zero’.
@DJHightower77
@DJHightower77 Жыл бұрын
Isn't "is null" still a problem in linq-expressions?
@GadgetCM
@GadgetCM Жыл бұрын
0:59 I have a seeded randomizer with a "random" value in here 😂 That's a thing I like about your content, Nick.
@GiulioBerti
@GiulioBerti Жыл бұрын
what is the difference between null and default?
@nickchapsas
@nickchapsas Жыл бұрын
null is always null but default can be null if the type is nullable but also not null if the value is not nullable. For example the default of int is 0 but the default of int? is null
@Sergio_Loureiro
@Sergio_Loureiro 11 ай бұрын
My 2 cents: 1. For `if (user is not null)` if your compiler version does not yet support the `not` keyword yet, you can write `if (!(user is null))` 2. How does one write a `is null` on a predicate expression tree? At least, my compiler does not support it. I will try `ReferenceEquals` or a cast to `(object?)` the next time I will be next the compiler.
@risingforce9648
@risingforce9648 9 ай бұрын
hey there! important you mentioned "unity" game engine about nullable things . thanks
@DoronGrinzaig
@DoronGrinzaig Жыл бұрын
This is ridiculous. If I or any of my colleagues or 3rd party tools overloaded == to return false for null checks with nulls, my smallest problem is the actual "wrong" null checks and actually the mess I have I have in my project (and the dumb shit people that work\ed on this project). That said, is null is indeed a nice way to write, that reminds python's is None.
@PaulMartins-pv6rg
@PaulMartins-pv6rg Жыл бұрын
I personally do not like the "not" variant - In your opinion, do you think 'is {}' should be avoided?
@nickchapsas
@nickchapsas Жыл бұрын
Yes, but it actually has a single usecase, and that's to check if something isn't null but then get the non-null type as a pattern matched type, to use in your block so for example: if(nullableItem is {} item){}
@aj-jc4cv
@aj-jc4cv Жыл бұрын
Re your q about feature creep, yes e.g. new deconstruction syntax and indices and ranges, I guess to attract the python crowd. Also complicated as you have things like records and have to remember if record structs properties are writable. Also new 'with' keyword and immutability etc. The null story isn't good, elvis operator, null coelescing and the assignment desparately needs Rusts approach with Option. A real smörgåsbord language.
@bluecup25
@bluecup25 10 ай бұрын
The "is null" syntax makes me think of SQL and that triggers some PTSD.
@AveN7ers
@AveN7ers Жыл бұрын
How do you know the Next method will return 7? I'm a TS/JS dev
@billy65bob
@billy65bob Жыл бұрын
He either ran it before, or has memorised the first few numbers from using that specific random seed so extensively. Same way I intrinsically know that 0xFFFFFF is 16777215 from seeing it so much...
@cruz1ale
@cruz1ale Жыл бұрын
I wish you could just do `if (user?)` { ... }. That would be consistent with the ?. operator. It'd just be syntactic sugar but still.
@test-rj2vl
@test-rj2vl 10 ай бұрын
Shouldn't be a issue if your team follow coding standards. In my team code that overrides == operator would never pass code review. If we want custom comparison we add methods and then use that method.
@DarKOscillator08
@DarKOscillator08 Жыл бұрын
And if someone has overridden the equality operator he is mayme doing this on purpose. By using "is null" you might miss this case and trying to work with an falsy object?
@nickchapsas
@nickchapsas Жыл бұрын
Incorrect because the responsibility can be shared. Consider that you define the type as nullable so you control the nullability and the logic. In that case is null is a must
@sanampakuwal
@sanampakuwal Жыл бұрын
I've been using "is null" and "is not null" for a while and was aware of operator overridden issue as well. you may say how did you figured it out earlier: well yes! I came to know while going through .NET PRs 😃
@Falanwe
@Falanwe Жыл бұрын
You bringing up Unity and saying to stick to == there is really interesting, because for me it's exactly the other way around. Often, your null check is just there because you want to know if something was initialized already, and the == in Unity will not let you do it if you're not on the main thread for Unity objects. Having (something == null) throw an exception is really a bad experience and justifies using other syntaxes without the issue.
@jackoberto01
@jackoberto01 Жыл бұрын
Well that's because any code interacting with the Unity API needs to run on the main thread as you say. Even if "someObject is null" may return false using it's transform may throw an exception. A common work around I've seen in some plugin is a "ContinueOnMainThread" extension method which works on async Tasks
@waynehamberg9248
@waynehamberg9248 Жыл бұрын
Hi Nick: What you failed to add in your video is why "Unit Testing?" If you had your application properly covered with unit tests then you could easily do a search for "== null" and simply do a replace with "is not null" and your unit tests would immediately pick up if you had a problem with your code. One of the biggest complaints I have with code is that top level code that isn't easily readable and understandable by no developers. I have seen in OnClick methods that are over 20,000 lines long where the code should read something like: DoThis(); DoThat(); if (Person.IsDoing == Activity.FunkyChicken) ShootThem(Person); DoThis() and DoThat() are easily understandable by anybody but I can very easily write unit tests for these types of methods. I can run my unit tests locally and my unit tests will fail if the code isn't written to the current standard.
@aligoren
@aligoren 11 ай бұрын
I learned object checking method thanks to resharper. I'm always using is and is not null way. It's more readable for me.
@JuvStudios
@JuvStudios Жыл бұрын
A good implementation of custom operator== should equal two nulls so I would say just use == like before.
@Falanwe
@Falanwe Жыл бұрын
Assuming a custom operator has a good implementation is just asking for trouble. Did you know for instance that (myObject == null) can actually throw a freaking exception in Unity?
@ExpensivePizza
@ExpensivePizza Жыл бұрын
@@Falanwe The idea that you would ever need assume any code has a bad implementation is pretty insane. Think about it. If code is not working as we expect it either means we've found a bug OR we don't actually understand why it works that way in the first place. The correct action is to fix the bug, read the documentation or implement a workaround NOT assume every possible implementation of that that code forever into the future as possibly wrong.
@Falanwe
@Falanwe Жыл бұрын
@@ExpensivePizzaThat's the right way to do it if you have control over that code. You don't always have it. In the cse of the Unity overload you absolutely don't.
@JuvStudios
@JuvStudios Жыл бұрын
@@Falanwe Then it's a bad implementation. I think introducing is null was a bad decision, just cast to object? in the case where you need real identity equality.
@ExpensivePizza
@ExpensivePizza Жыл бұрын
@@Falanwe Unity has something like a million developers using it. I'm one of them. No doubt Unity has some confusing behavior's but I find it very hard to believe the Unity team didn't think about the pros and cons of their implementation. In other words, Unity is working exactly the way it was designed. It's well documented and tested. So in that case I would say it's about learning not fixing.
@SamMackrill
@SamMackrill Жыл бұрын
So what about ?. and ?? are they using == or is ?
@phizc
@phizc Жыл бұрын
They use "is", that is reference equality.
@quranthecompanion4528
@quranthecompanion4528 Жыл бұрын
Yeah. we have been using "is null" and "is not null". good to see C# is coming a long way..
@user-ud2oo8id2m
@user-ud2oo8id2m 11 ай бұрын
Am I missing something? Why not use is IsNullOrEmpty?
@xxgn
@xxgn 11 ай бұрын
He's talking about null checking in general. The video is not string-specific. Also, IsNullOrEmpty has different semantics, since it returns true when given an empty string.
@PrzygodazUnity
@PrzygodazUnity Жыл бұрын
You can use "is" with you cannot overload :)
@mahe4
@mahe4 10 ай бұрын
if some one overloads the equals operator on a class in a way, that simple null checks don't work any more, then i chop their hands of.
@vkishan2089
@vkishan2089 11 ай бұрын
This is were I differ from your explanation, if something is overridden it should be used.
@cwevers
@cwevers Жыл бұрын
Too much overstatement on operator overloads. These should just be implemented correctly by their respective authors, if they are even used. I continue to use != null
@TheOneAndOnlySecrest
@TheOneAndOnlySecrest Жыл бұрын
One interesting part which is missing imho is the behavior of nullable structs with is. Because however structs can never be null AND is does not call Equals internally, default(int?) is null returns true. Nullables are a strange thing because the CLI actually chooses the Struct or null depending on your usage in IL code. int? = 1 will be an int, but int? = null will be a null ref. Nullable is just a lie as far as I know :D Another interesting part is the behavior with ref values if you use Unsafe.NullRef you can actually create a struct with a null value. Accessing it will lead to nullref exceptions.
@JasonEmanuel
@JasonEmanuel 10 ай бұрын
Ugh... Now I have a headache and a pile of code to review. Thanks for sharing!
@DiomedesDominguez
@DiomedesDominguez 8 ай бұрын
Now, lets talk about the use cases of the goto statement in C#
@F1nalspace
@F1nalspace Жыл бұрын
I knew about operator overloading == and !=, but "is null" or is "is not null" is new for me and i really like that. But the pattern matching thing is really weird, especially when you match for deeper properties... i would rather do multiple checks or even use ? operator and then check for null instead.
@AbhinavKulshreshtha
@AbhinavKulshreshtha Жыл бұрын
This makes me think that Java's decision to not support operator overloading is a good thing. My version of checking not null was " if (!(obj is null))"
@protox4
@protox4 Жыл бұрын
Hard disagree. Just because a tool can be abused doesn't mean it's a bad tool.
@Ferrolune
@Ferrolune 11 ай бұрын
Personally, I avoid using null checks all together, for as long as it is possible. The idea is that if you need a null check, you are in an invalid state and therefore your code is doing something it shouldn't; the code breaks, allowing you to rethink why it just did, allowing you to find the real cause as to why the data is in said state. That's not to say that I avoid null checks completely, but rather use them extremely sparingly once I'm sure there is no other way.
@tylerwilson3027
@tylerwilson3027 Жыл бұрын
I would love to a see a related video talking about nullability in C#. Coming from Swift/Kotlin we have explicit null types, but it seems like in C# there is a mix of both. Likely from the backwards compatibility requirements you mentioned. Thank you for the great content!
@prouleau4440
@prouleau4440 Жыл бұрын
From my point of view, many confusions are caused by the way C# handle the String class. It is a reference type, but they implemented many hacks to make it usable as a value type in many situations. And since String is very common in the code, people get confused because they do not realize what are the special use-cases with String. On top of that it is an COW type.
@qj0n
@qj0n Жыл бұрын
Long story short, structs have explicit nullability in types, classes have optional compile-time nullability attributes, but after compilation all are nullable
@tylerwilson3027
@tylerwilson3027 Жыл бұрын
@@prouleau4440 Yeah, I am a relaté newbie in C#, and was confused when the IDE (VS for Mac) would give me warnings when I used string? but not when I do int?. Then I try to add the Nullable to the project, and everything goes to hell. 🙂
@MichaelBattaglia
@MichaelBattaglia Жыл бұрын
I am from the future and c# and vb are indistinguishable.
@jpsytaccount
@jpsytaccount Жыл бұрын
Haven’t you already done a couple videos on this topic already?
@nickchapsas
@nickchapsas Жыл бұрын
I've done a short on it and an old "The evolution of null" video but not a video on my new format on this topic
@ti83magic
@ti83magic Жыл бұрын
I thought the same as well, I know I learned this from you, over a year ago :) might have been a short then.
6 INSANE Things You Didn't Know You Could Write in C#
12:26
Nick Chapsas
Рет қаралды 50 М.
C# Nullable reference types - No more null reference exceptions!
18:06
Watermelon Cat?! 🙀 #cat #cute #kitten
00:56
Stocat
Рет қаралды 7 МЛН
The Worlds Most Powerfull Batteries !
00:48
Woody & Kleiny
Рет қаралды 26 МЛН
ONE MORE SUBSCRIBER FOR 6 MILLION!
00:38
Horror Skunx
Рет қаралды 15 МЛН
Why You Should Always Help Others ❤️
00:40
Alan Chikin Chow
Рет қаралды 31 МЛН
3 .NET "Best Practices" I Changed My Mind About
10:16
Nick Chapsas
Рет қаралды 99 М.
How IEnumerable can kill your performance in C#
11:02
Nick Chapsas
Рет қаралды 112 М.
Manage Nulls Like a Boss and Never Fail!
21:43
Zoran Horvat
Рет қаралды 10 М.
The Easiest Way to Measure Your Method’s Performance in C#
12:51
Nick Chapsas
Рет қаралды 74 М.
.NET 9 Fixed Exceptions but Still Don’t Use Them
10:01
Nick Chapsas
Рет қаралды 39 М.
The New .NET 9 HybridCache That You Must Upgrade To!
14:34
Nick Chapsas
Рет қаралды 41 М.
What are record types in C# and how they ACTUALLY work
15:36
Nick Chapsas
Рет қаралды 116 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
Watermelon Cat?! 🙀 #cat #cute #kitten
00:56
Stocat
Рет қаралды 7 МЛН