Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
After a recent Visual Studio update, I am now getting little green dots appearing beneath code, indicating places I could modernise and presumably improve my code to use the latest C# features.

One of these recommends testing for null using the is keyword. Eg.

Don't write...

C#
if( x == null )


Write this instead...

C#
if( x is null )


I'd like to understand the advantage of this and I don't seem to be able to find a simple answer to this anywhere. Anyone?

What I have tried:

I've tried Googling around but don't seem to be able to find a straight answer.
Posted
Updated 24-Aug-18 0:25am
Comments
Jochen Arndt 24-Aug-18 6:20am    
First hit for "c# is null vs == null":
https://stackoverflow.com/questions/40676426/what-is-the-difference-between-x-is-null-and-x-null

The straight forward answer is in that thread:
There is no difference for this special case (checking for null).
Patrick Skelton 24-Aug-18 7:04am    
I think I googled 'what is the advantage of c# is operator'.

There is a detailed blog post that can answer this for you: "is null" versus "== null" in C#[^]
 
Share this answer
 
I googled "== null vs is null" and this was the first result

c# - What is the difference between "x is null" and "x == null"? - Stack Overflow[^]

There are many more results if you search yourself.

The main issue seems to be that you can overload "==" to change its behaviour so when you use "== null" you have no guarantee what code is actually being called and how "== null" is being defined. For example if I have a Person class I could overload == for Person to say that if the person has no ID then it is null. When your code uses "if (p == null)" the result might be "true" despite the variable "p" not actually being a null reference.

However when you use "is" that can't be overloaded so checking "is null" gives a more accurate view of if the variable is a null reference or not.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900