0

In a code review that I have made today to one of my team mates, I have seen him checking properties for null with the is keyword, like:

if(myVariable is null)
{
    //do something
}

I was tempted to disagree of this type of checking, but I don't feel so confident on my knowledge about it. Is it really okay to check for null like this?

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • What is the type of the property? – EnterTheCode Mar 14 '18 at 16:52
  • @EnterTheCode it has many different types as it is used in a lot of places in the code, but I can assure you that it is a reference type which is valid to be checked for null. – meJustAndrew Mar 14 '18 at 16:54
  • 3
    Well I didnt even know that would compile - always use this `object.ReferenceEquals(null, myVariable)` - not entirely sure why but someone once told me "use that" – Rand Random Mar 14 '18 at 16:55
  • 1
    https://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/ – Daxtron2 Mar 14 '18 at 16:56
  • 1
    `if(myVariable is null)` is compiling ? – rahulaga-msft Mar 14 '18 at 16:56
  • I had Resharper recently suggest changing a call to `ReferenceEquals` to `is null` instead. – juharr Mar 14 '18 at 16:57
  • 2
    @meJustAndrew The following question seems to answer your question: https://stackoverflow.com/questions/44607581/what-is-a-difference-between-foo-is-null-and-foo-null. – EnterTheCode Mar 14 '18 at 16:57
  • @ckuri, I just want to add that `is null` will compile only if you have a reference type, but `ReferenceEquals(null, x)` always compiles no matter to what type your objects have. – meJustAndrew Mar 14 '18 at 17:04
  • @RahulAgarwal: It is a new feature for C# 7. See https://blogs.msdn.microsoft.com/seteplia/2017/10/16/dissecting-the-pattern-matching-in-c-7/ for the details. – Eric Lippert Mar 14 '18 at 19:03
  • 1
    @meJustAndrew: Just to clarify: the fact that `is null` fails at compile time when `x` is not a reference type is a *feature*. `ReferenceEquals(null, x)` for non-reference-type `x` is almost always an error. If `x` is a nullable value type then use `!x.HasValue`, or `x == null)`; if `x` is a non-nullable value type then it will always be false. Either way, it is a mistake, and so it should be caught at compile time. – Eric Lippert Mar 14 '18 at 19:06
  • Indeed @EricLippert , I knew this is a feature and I am happy because it was built this way, because it can be confusing in the case of `ReferenceEquals(value, value)` people would be tempted to think that the result of this will always be true (as Resharper is suggesting) while in fact it is actually false for value types. – meJustAndrew Mar 15 '18 at 14:10

0 Answers0