- Home /
Does pattern matching verify object lifetime and null references
With C# 9.0 and newer, various pattern match forms were added. Here's an example:
Rigidbody? Rb = //...
//Style #1
if ( Rb is null ) { //<-- pattern match
}
//Style #2
if ( Rb is not null ) {
}
//Style #3
if ( Rb is { } RbVal ) {
}
My question then is, do the pattern match checks also check object lifetime and null references properly? Much like how we can't use null propagation and instead must use the ' == null ' check, I'm wondering if the same goes for pattern matches.
Answer by Hellium · Dec 22, 2021 at 08:23 AM
The documentation is quite explicit
The compiler guarantees that no user-overloaded equality operator == is invoked when expression x is null is evaluated.
Since the comparison between null and a Unity object involves some custom code, I am pretty sure you can't use this syntax to check if the object is (fake) null, and you'll have to stick with the good old if(Rb)
or if(Rb == null)
syntax.
I see, thank you! I tried looking around quite a bit for an official piece of unity documentation giving an answer, but never even thought to check the actual .NET documentation itself.
Your answer
![](https://koobas.hobune.stream/wayback/20220613050826im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Checking if an object is null, results in NRE 1 Answer
If statement is being ignored 1 Answer
Check if Array.GetValue(i) is null 1 Answer