Question

I installed Reshaper today on my PC to check it out and whenever I have following statement in my code I get an info from Resharper that comparing to Null is not necessary. Why?

This is the statement:

if (dataGrid.ItemsSource != null && dataGrid.ItemsSource is DataGridCollectionView)

I am checking if the type is the one I want it to be and if the value is not Null.

It makes sense for me to ask for this because the type might be true though the value might be still Null. I guess I must be missing something in documentation about this.

Why does Reshaper say I dont need to compare to null?

What am I missing?

Was it helpful?

Solution

The is operator will always return false if the object is null, so you do not need to check for null before testing the type.

From the documentation:

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

OTHER TIPS

dataGrid.ItemsSource is DataGridCollectionView means "dataGrid.ItemsSource is an instance of DataGridCollectionView"; if it's an instance (of anything), it can't be null, so the null check is redundant.

null will always return false from an is test, so the null check doesn't achieve anything that the is test doesn't already do. The only insane edge case where this could misbehave is if you had a property that returned different things on successive invocations - so if the first .ItemsSource returned something very different to the second .ItemsSource. Which would be dangerous and self-inflicted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top